+ All Categories
Home > Documents > 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more...

1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more...

Date post: 28-Dec-2015
Category:
Upload: jocelyn-cunningham
View: 223 times
Download: 8 times
Share this document with a friend
Popular Tags:
60
1 CHAPTER 10 CHAPTER 10 More Complex Business More Complex Business Rules Rules
Transcript
Page 1: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

1

CHAPTER 10CHAPTER 10More Complex Business More Complex Business

Rules Rules

Page 2: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

2

More Complex Business RulesMore Complex Business Rules

Entity objects can do more than just be representations Entity objects can do more than just be representations of data. They can also encapsulate the business rules of data. They can also encapsulate the business rules pertaining to the data they represent. pertaining to the data they represent.

An entity object can:An entity object can:

• Enforce validation rules for attribute valuesEnforce validation rules for attribute values

• Calculate default values for attributesCalculate default values for attributes

• Automatically calculate the values of transient Automatically calculate the values of transient attributesattributes

• Automatically react to data changes Automatically react to data changes

Page 3: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

3

Overview of Entity ClassesOverview of Entity Classes

Entity object definitions are handled by three classes in the ADF BC Entity object definitions are handled by three classes in the ADF BC library. They are referred to as the library. They are referred to as the base entity classesbase entity classes::

• oracle.jbo.server.EntityImploracle.jbo.server.EntityImpl Each instance represents one Each instance represents one row in a database table. This class has all the methods needed to row in a database table. This class has all the methods needed to read, update, insert, delete, and lock rows. read, update, insert, delete, and lock rows.

• oracle.jbo.server.EntityDefImploracle.jbo.server.EntityDefImpl Instances of this class act as Instances of this class act as wrappers for the entity object definition XML files. The class wrappers for the entity object definition XML files. The class contains methods allowing you to dynamically change the contains methods allowing you to dynamically change the definition of the entity object itself – to add or remove entity definition of the entity object itself – to add or remove entity attributes or to change the properties of these attributes.attributes or to change the properties of these attributes.

• oracle.jbo.server.EntityCacheoracle.jbo.server.EntityCache An instance acts as an entity An instance acts as an entity cache – a memory location holding instances of a particular cache – a memory location holding instances of a particular entity object definition in use in a single transaction. Methods entity object definition in use in a single transaction. Methods are provided that manipulate rows in the cache. You normally do are provided that manipulate rows in the cache. You normally do not use these methods directly. They are for internal use.not use these methods directly. They are for internal use.

Page 4: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

4

Overview of Entity ClassesOverview of Entity Classes

If you need further customization, you can generate custom If you need further customization, you can generate custom entity classes that extends one or more of them. For entity classes that extends one or more of them. For example, for a particular entity object definition, example, for a particular entity object definition, Departments, you could generate any or all of the following:Departments, you could generate any or all of the following:

• DepartmentsImplDepartmentsImpl An entity object class, which extendsAn entity object class, which extends EntityImplEntityImpl

• DepartmentsDefImplDepartmentsDefImpl An entity definition class, which extendsAn entity definition class, which extends EntityDefImplEntityDefImpl

• DepartmentsCollImplDepartmentsCollImpl An entity collection class, which extendsAn entity collection class, which extends EntityCacheEntityCache

These classes may be customized for a particular These classes may be customized for a particular application.application.

Page 5: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

5

Entity Object ClassesEntity Object Classes

An entity object class is a subclass of An entity object class is a subclass of EntityImplEntityImpl that a that a particular object definition can use to represent its particular object definition can use to represent its instances. They have the same name as the entity instances. They have the same name as the entity object definition with an "object definition with an "ImplImpl" suffix. The entity " suffix. The entity object definition "object definition "DepartmentsDepartments“, for example, would “, for example, would have an implementation class called have an implementation class called ""DepartmentsImplDepartmentsImpl". ".

Page 6: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

6

Entity Attribute AccessorsEntity Attribute Accessors

Entity object classes provide accessors (getters and Entity object classes provide accessors (getters and setters) for each attribute. For example, setters) for each attribute. For example, DepartmentsImplDepartmentsImpl will by default contain the will by default contain the getDepartmentId() getDepartmentId() and and setDepartmentId()setDepartmentId() methods. methods.

EntityImpl contains the getAttribute() and setAttribute() methodswhich also allow you to retrieve and change attribute values, but accessorsin the entity object class have two advantages.

Page 7: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

7

Entity Attribute Accessors Are Entity Attribute Accessors Are TypesafeTypesafe

Entity attribute accessors are Entity attribute accessors are typesafetypesafe, they take fully , they take fully typed objects as parameters and have fully typed typed objects as parameters and have fully typed return values.return values.

For example, For example, DepartmentsImplDepartmentsImpl will by default will by default contain the method contain the method getDepartmentId()getDepartmentId(), which , which returns a returns a NumberNumber, and the method , and the method setDepartmentIdsetDepartmentId()(), which returns void and takes a , which returns void and takes a NumberNumber argument. argument.

The following code causes compile-time errors.The following code causes compile-time errors.

String myDeptId = myDepartmentsImpl.getDepartmentId();// because the return-type is not a Number

myDepartmentsImpl.setDepartmentId( “25” ); // because the parameter is not a Number

Number myDeptId = myDepartmentsImpl.getDeptId();// because the attribute name is not correct

Page 8: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

8

Entity Attribute Accessors Are Entity Attribute Accessors Are TypesafeTypesafe

EntityImplEntityImpl's's attributes can still be accessed directly using the following attributes can still be accessed directly using the following methods (although they are not methods (although they are not typesafetypesafe):):

• EntityImpl.getAttribute()EntityImpl.getAttribute() Takes a Takes a StringString (attribute name) argument and returns a (attribute name) argument and returns a java.lang.Objectjava.lang.Object

• EntityImpl.setAttribute()EntityImpl.setAttribute()Takes a Takes a StringString (attribute name) and an (attribute name) and an ObjectObject as arguments as arguments

If you forget the Java type of your attributes you will not get a compile-If you forget the Java type of your attributes you will not get a compile-time error, but the application will throw an exception at runtime (making time error, but the application will throw an exception at runtime (making things harder to debug).things harder to debug).

Neither of these lines will cause a compile-time error, but they will throw Neither of these lines will cause a compile-time error, but they will throw exceptions at run-time: exceptions at run-time:

String myDeptId = (String)myEntityImpl.getAttribute("DepartmentId");myEntityImpl.getAttribute("DepartmentId“, “25”);

Page 9: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

9

Entity Attribute Accessors Are Entity Attribute Accessors Are TypesafeTypesafe

Using entity attribute accessors can make it easier to Using entity attribute accessors can make it easier to debug typos in attribute names.debug typos in attribute names.

For example, the first line below will cause a compile-For example, the first line below will cause a compile-time error, and the second line below will throw an time error, and the second line below will throw an exception at run-time.exception at run-time.Number myDeptId = myDepartmentsImpl.getDepartmentId();Number myDeptId = myEntityImpl.getAttribute("DepartmentId“);

Page 10: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

10

Entity Object Classes Allow You to Write Custom Entity Object Classes Allow You to Write Custom Business LogicBusiness Logic

The accessors in entity object classes can be edited if The accessors in entity object classes can be edited if necessary. You can write code in accessors to perform necessary. You can write code in accessors to perform actions such as:actions such as:

• Restrict access to dataRestrict access to data

• Validate changesValidate changes

• Trigger events when an attribute is changedTrigger events when an attribute is changed

You must implement complex requirements in an entity You must implement complex requirements in an entity object class. object class.

Page 11: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

11

Overriding Methods in EntityImplOverriding Methods in EntityImplYou can also override various methods in the You can also override various methods in the EntityImplEntityImpl class to implement other business logic. By class to implement other business logic. By overriding the overriding the EntityImpl.create()EntityImpl.create() method, for method, for example, you can implement defaulting logic or trigger example, you can implement defaulting logic or trigger events whenever a row is created. events whenever a row is created.

Page 12: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

12

Entity Definition ClassesEntity Definition Classes

Entity definitionEntity definition classes extend classes extend oracle.jbo.server.EntityDefImploracle.jbo.server.EntityDefImpl..

Unlike entity object classes, which are usually generated for Unlike entity object classes, which are usually generated for most entity objects, there are only two reasons for creating an most entity objects, there are only two reasons for creating an entity definition class are:entity definition class are:

• To override the method To override the method EntityDefImpl.createDef()EntityDefImpl.createDef(), , which is called as soon as the entity object is loaded into which is called as soon as the entity object is loaded into memory. This allows you to dynamically change the memory. This allows you to dynamically change the definition of the entity object without writing code in every definition of the entity object without writing code in every application that uses it.application that uses it.

• The need to provide a place to put a custom method that The need to provide a place to put a custom method that affects an entire table, as opposed to a single row (which affects an entire table, as opposed to a single row (which should be in an entity object class) or all rows returned by should be in an entity object class) or all rows returned by a particular query (which should be in a view object class).a particular query (which should be in a view object class).

Page 13: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

13

Entity Collection ClassesEntity Collection Classes Suppose an application has just inserted a row into, or accessed a row Suppose an application has just inserted a row into, or accessed a row from, the from, the DEPARTMENTSDEPARTMENTS table. When it did, an instance of the table. When it did, an instance of the DepartmentImplDepartmentImpl object was created. Usually the application will need object was created. Usually the application will need to access the row again in the near future, so rather than destroying to access the row again in the near future, so rather than destroying the object, the object, ADF BCADF BC stores it in a cache called the stores it in a cache called the entity cacheentity cache..

When a row is changed, instead of making a time-consuming round trip When a row is changed, instead of making a time-consuming round trip to the database, ADF BC simply makes the change to the to the database, ADF BC simply makes the change to the DepartmentImplDepartmentImpl object in the entity cache until the transaction is object in the entity cache until the transaction is committed or the change is manually posted.committed or the change is manually posted.

Usually an entity cache is implemented by an object of the type Usually an entity cache is implemented by an object of the type oracle.jbo.server.EntityCacheoracle.jbo.server.EntityCache. You can also generate an . You can also generate an entity entity collection classcollection class (extended from (extended from EntityCacheEntityCache) if you need to change ) if you need to change the behavior of the entity cache. the behavior of the entity cache. Entity collection classesEntity collection classes have the have the same name as the entity object with a "same name as the entity object with a "CollImplCollImpl" suffix. For example, " suffix. For example, the "the "DepartmentsDepartments" entity object would have the definition class called " entity object would have the definition class called ""DepartmentsCollImplDepartmentsCollImpl". ".

Page 14: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

14

Manipulating Attribute ValuesManipulating Attribute Values You can manipulate domains from the You can manipulate domains from the oracle.jbo.domainoracle.jbo.domain package. package. There are two options you can use.There are two options you can use.

1.1. Convert the domain to a standard java type. You can now use Convert the domain to a standard java type. You can now use methods and methods and operators provided by Java. When finished, you can re-create the operators provided by Java. When finished, you can re-create the domain by passingdomain by passing the standard Java type to the domain’s constructor. For example: the standard Java type to the domain’s constructor. For example:

2.2. You can work directly with the domains using methods provided by You can work directly with the domains using methods provided by domain classes.domain classes.

Each option has its own advantages.Each option has its own advantages.

int salaryValue = salary.intValue();salaryValue++; // manipulate the datasalary = new Number(salaryValue);

Page 15: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

15

Manipulating Attribute ValuesManipulating Attribute Values

Domain Conversion MethodsNumber int intValue(), long longValue(), short shortValue(), float floatValue(), double doubleValue(), byte byteValue(), java.math.BigDecimal bigDecimalValue(),

java.math.BigInteger bigIntegerValue()Date java.lang.Date toDate()Array java.lang.Object[] getArray()BFileDomain,BlobDomain,ClobDomain byte[] toByteArray()

Conversion methods:

Page 16: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

16

Manipulating Attribute ValuesManipulating Attribute Values

Domains based on Oracle types have accessor methods Domains based on Oracle types have accessor methods to retrieve and change values.to retrieve and change values.

For example, if the object For example, if the object myAddressmyAddress is of is of AddressTypeAddressType (from Chapter 9), you can append “ (from Chapter 9), you can append “--12341234” to ” to myAddressmyAddress’s ’s PostalCodePostalCode attribute as attribute as follows:follows: String myPostalCode = myAddress.getPostalCode();

myPostalCode = myPostalCode + “-1234”;myAddress.setPostalCode( myPostalCode );

Page 17: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

17

Manipulating Attribute ValuesManipulating Attribute Values

Domain Conversion MethodsNumber add(), subtract(), multiply(), divide(), increment(), abs(), exp(), sin(), cos(), tan(), compareTo()Date addJulianDays(), addMonths(), round(), lastDayInMonth(), diffInMonths(), getCurrentDate()BFileDomain getInputStream(), getOutputStream, closeOutputStream()BlobDomain getBinaryStream(),getBinaryOutputStream(),

closeOutputStream(), getBytes(), getLength()ClobDomain getCharacterStream(),getCharacterOutputStream(), getSubstring(), getLength()

Conversion methods:

Page 18: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

18

Attribute-Level ValidationAttribute-Level Validation

The simplest kind of business rule is one that needs to The simplest kind of business rule is one that needs to fire whenever an attribute is changed, to make sure the fire whenever an attribute is changed, to make sure the value passes some test.value passes some test.

You may want to implement a rule that email addresses You may want to implement a rule that email addresses must have a length of at most eight characters. Logic must have a length of at most eight characters. Logic like this is called attribute-level validation because it is like this is called attribute-level validation because it is intended to check the value in a single attribute in a intended to check the value in a single attribute in a single row. ADF provides three ways to do this:single row. ADF provides three ways to do this:

• Validation rulesValidation rules• Validation domainsValidation domains• Setter method validationSetter method validation

Page 19: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

19

Validation RulesValidation Rules

Validation rules are Java classes that can be attached Validation rules are Java classes that can be attached to entity attributes or entire entity object definitions to entity attributes or entire entity object definitions using the using the Entity Object EditorEntity Object Editor..

A validation rule contains a method that throws an A validation rule contains a method that throws an exception whenever a potential attribute value does not exception whenever a potential attribute value does not pass some test. The pass some test. The EntityImplEntityImpl class will call this class will call this method whenever an application attempts to change method whenever an application attempts to change the attribute value; the value is only changed if the the attribute value; the value is only changed if the exception is not thrown.exception is not thrown.

Page 20: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

20

Validation RulesValidation Rules For example, a validation rule called the For example, a validation rule called the CompareValidatorCompareValidator has has been added to the been added to the SalarySalary entity attribute in the following: entity attribute in the following:

<AttributeName="Salary"IsNotNull="true"Type="oracle.jbo.domain.Number"...TableName="EMPLOYEES" ><CompareValidationBean

OnAttribute="Salary"OperandType="LITERAL"CompareType="GREATERTHAN"CompareValue="1000" >

</CompareValidationBean></Attribute>

The CompareValidationBean element nested inside the Attribute element implements the CompareValidator rule.

Page 21: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

21

Built-In Validation RulesBuilt-In Validation Rules

JD provides four built-in validation rules for attributes. JD provides four built-in validation rules for attributes. Three of which can be used without writing code.Three of which can be used without writing code.

• CompareValidatorCompareValidator

• ListValidatorListValidator

• RangeValidatorRangeValidator

• MethodValidatorMethodValidator

Page 22: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

22

The CompareValidator The CompareValidator A A CompareValidatorCompareValidator requires an attribute's value be requires an attribute's value be in some relation to a specified value. The relations in some relation to a specified value. The relations available are:available are:

• EqualsEquals

• NotEqualsNotEquals

• LessThanLessThan

• GreaterThanGreaterThan

• LessOrEqualToLessOrEqualTo

• GreaterOrEqualToGreaterOrEqualTo

Page 23: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

23

The CompareValidator The CompareValidator The simplest use is to require an attribute's value be in The simplest use is to require an attribute's value be in some relation to a particular literal value specified in some relation to a particular literal value specified in the validation rule. Here the Salary attribute's value the validation rule. Here the Salary attribute's value must be greater than 1000:must be greater than 1000:

Page 24: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

24

The CompareValidator The CompareValidator A CompareValidatorA CompareValidator can be used to enforce a relation can be used to enforce a relation to a column from a query or a transient attribute. to a column from a query or a transient attribute. Besides Besides Literal ValueLiteral Value, a , a QueryQuery ResultResult or or View View Object AttributeObject Attribute can be selected from the can be selected from the CompareCompare WithWith dropdown. dropdown.

With With QueryQuery ResultResult, the attribute is compared with the , the attribute is compared with the value in the first column of the first row in the result value in the first column of the first row in the result set returned by the SQL query entered. The query may set returned by the SQL query entered. The query may also be created to return only one column and row.also be created to return only one column and row.

Page 25: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

25

The CompareValidator The CompareValidator The screen shot below shows a single-row, single The screen shot below shows a single-row, single column query used to enforce the rule that nobody can column query used to enforce the rule that nobody can have a higher salary than the company's president: have a higher salary than the company's president:

Page 26: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

26

The CompareValidator The CompareValidator With the With the View Object AttributeView Object Attribute, the value will be compared to , the value will be compared to the value of the selected view row attribute for the first view row.the value of the selected view row attribute for the first view row.

The screen shot below shows how to require the first view row in The screen shot below shows how to require the first view row in EmployeesViewEmployeesView to have the maximum salary for all the to have the maximum salary for all the employees: employees:

The problem with using default view objects is that there is very little control over which view row is first. Therefore, using the View Object Attribute is not very useful.

Page 27: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

27

The ListValidatorThe ListValidatorThe The ListValidatorListValidator requires an attribute's value either requires an attribute's value either to be in a list of possible values, or not to be in a list of to be in a list of possible values, or not to be in a list of excluded values. The list of values can be created from:excluded values. The list of values can be created from:

• Literal valuesLiteral values

• A query resultA query result

• A view attributeA view attribute

Page 28: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

28

The ListValidatorThe ListValidatorThe list of literal values can simply be keyed in as The list of literal values can simply be keyed in as shown below: shown below:

Page 29: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

29

The ListValidatorThe ListValidatorWith a SQL query, the values for the list come from the first With a SQL query, the values for the list come from the first column (as in the column (as in the CompareValidatorCompareValidator). Unlike the ). Unlike the CompareValidatorCompareValidator though, a though, a ListValidatorListValidator looks at all rows in looks at all rows in the query result.the query result.

The example below uses a SQL statement to require the The example below uses a SQL statement to require the EmployeesEmployees JobIdJobId attribute match a attribute match a JOB_IDJOB_ID in the in the JOBSJOBS table. table.

Page 30: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

30

The ListValidatorThe ListValidatorThe The ListValidatorListValidator works the same way with a view works the same way with a view attribute. The list is formed from the value of the view attribute. The list is formed from the value of the view attribute in every row the view object returns.attribute in every row the view object returns.

For example, you could select For example, you could select JobIdJobId from the from the JobsViewJobsView to have the same effect as the SQL to have the same effect as the SQL statement above (with the added advantages that the statement above (with the added advantages that the ADF BC framework would cache the query values for ADF BC framework would cache the query values for you and use any logic you added to the you and use any logic you added to the JobsViewJobsView view view object). object).

Page 31: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

31

The ListValidatorThe ListValidatorExample Example ListValidatorListValidator for for DepartmentIdDepartmentId ListValidatorListValidator screen: screen:

Page 32: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

32

The ListValidatorThe ListValidatorGenerated statements in the Generated statements in the Departments.xmlDepartments.xml file: file:

Page 33: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

33

The RangeValidator The RangeValidator The The RangeValidatorRangeValidator requires the attribute's value to be either requires the attribute's value to be either between two possible values or outside ("between two possible values or outside ("notBetweennotBetween") a range ") a range of excluded values.of excluded values.

A A RangeValidatorRangeValidator cannot use a query or view object to calculate cannot use a query or view object to calculate the endpoints of the range. The the endpoints of the range. The MUSTMUST be specified as literals, as be specified as literals, as show below: show below:

Page 34: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

34

The MethodValidator The MethodValidator If none of the other validators provide the attribute If none of the other validators provide the attribute validation you want, you can use the validation you want, you can use the MethodValidatorMethodValidator to define it yourself. to define it yourself.

MethodValidatorMethodValidator calls a Java method in the entity calls a Java method in the entity object class. This method must take a single argument object class. This method must take a single argument with the following requirements:with the following requirements:

• Of the same type as the attributeOf the same type as the attribute

• It must be It must be publicpublic

• It must return a It must return a booleanboolean value value

Page 35: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

35

The MethodValidator The MethodValidator For example, the company in the HR schema requires For example, the company in the HR schema requires that all email addresses (that all email addresses (EmailEmail attribute of the attribute of the EmployeesEmployees entity object) have eight or less uppercase entity object) have eight or less uppercase alphabetic characters. A method, like the one below, alphabetic characters. A method, like the one below, can be coded to return can be coded to return truetrue if the email address is if the email address is valid or valid or falsefalse if it is not. if it is not.

Page 36: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

36

The MethodValidator The MethodValidator You can then apply the You can then apply the MethodValidatorMethodValidator to call the to call the method defined above as shown below:method defined above as shown below:

Page 37: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

37

The MethodValidator The MethodValidator Example Example MethodValidatorMethodValidator for for DepartmentIdDepartmentId

MethodValidatorMethodValidator screen: screen:

Page 38: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

38

The MethodValidator The MethodValidator Code for the Code for the validateDept()validateDept() method in the method in the DepartmentsImpl.javaDepartmentsImpl.java file:file:

Page 39: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

39

When Validation Fails When Validation Fails When a client tries to set a value for an attribute which When a client tries to set a value for an attribute which violates a validation rule, two things happen:violates a validation rule, two things happen:

• If the validation rule was a If the validation rule was a MethodValidatorMethodValidator, , the entity object class throws an the entity object class throws an oracle.jbo.ValidationExceptionoracle.jbo.ValidationException..

• If the validation rule was not a If the validation rule was not a MethodValidatorMethodValidator, the entity object class throws , the entity object class throws an an oracle.jbo.AttrSetValExceptionoracle.jbo.AttrSetValException..

These exceptions can be caught in your client, and These exceptions can be caught in your client, and dealt with however you want. The exceptions contain dealt with however you want. The exceptions contain error messages you can set when the validation rule is error messages you can set when the validation rule is created. created.

Page 40: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

40

Setter Method Validation Setter Method Validation Validation rules are simple, declarative, and quick to Validation rules are simple, declarative, and quick to use. But, for more complex business rules, programs use. But, for more complex business rules, programs need to use Java. Using the need to use Java. Using the MethodValidatorMethodValidator above above on an attribute is one way of using Java, but business on an attribute is one way of using Java, but business logic can be coded directly in the logic can be coded directly in the settersetter of an entity of an entity attribute.attribute.JDeveloper creates simple setters that do nothing but JDeveloper creates simple setters that do nothing but call a single method (call a single method (setAttributeInternal()setAttributeInternal()) when it ) when it generates an entity object class.generates an entity object class.

public void setEmail(String value){ setAttributeInternal(EMAIL, value);}

Page 41: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

41

Setter Method Validation Setter Method Validation The The setAttributeInternal()setAttributeInternal() method takes an method takes an intint and and an an ObjectObject. The . The intint corresponds to a particular entity corresponds to a particular entity attribute (in attribute (in EmployeesImplEmployeesImpl, the constant , the constant EMAILEMAIL equals the value equals the value 33).).

protected static final int EMPLOYEEID = 0;protected static final int FIRSTNAME = 1;protected static final int LASTNAME = 2;protected static final int EMAIL = 3;protected static final int PHONENUMBER = 4;

The Object corresponds to a value to set the attribute to.

Page 42: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

42

Setter Method Validation Setter Method Validation The difference between The difference between setAttributeInternal()setAttributeInternal() (takes an (takes an intint to to identify the attribute) and identify the attribute) and setAttribute()setAttribute() (takes a (takes a StringString to to identify the attribute), is that the identify the attribute), is that the setAttribute()setAttribute() calls the setter calls the setter method (if setters have been generated), but the method (if setters have been generated), but the setAttributeInternal()setAttributeInternal() simply checks the XML for validation simply checks the XML for validation rules and then sets the attribute's value.rules and then sets the attribute's value.

When you call When you call EntityImpl.setAttribute()EntityImpl.setAttribute() or an entity object's or an entity object's setter method, the first thing that happens is that the Java code in setter method, the first thing that happens is that the Java code in the setter will be executed. At some point the setter method the setter will be executed. At some point the setter method should call should call setAttributeInternal()setAttributeInternal() as shown above. When that as shown above. When that method is called, it will check for validation rules, and if none are method is called, it will check for validation rules, and if none are found, or all of them are passed, it will set the attribute's value. found, or all of them are passed, it will set the attribute's value. public void setEmail( String value ) throws oracle.jbo.jboException { if ( value.length <= 8 ) { setAttributeInternal( EMAIL, value ); } else { throw new oracle.jbo.JboException ( “An email address must have at most 8 characters.” ); }}

Page 43: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

43

Stages of validationStages of validation

View object layer calls setAttribute("EMAIL", "SKING")View object layer calls setAttribute("EMAIL", "SKING")

setAttribute() calls setEmail("SKING") setAttribute() calls setEmail("SKING")

setEmail() executes Java business logic setEmail() executes Java business logic

setEmail() calls setAttributeInternal("EMAIL", "SKING")setEmail() calls setAttributeInternal("EMAIL", "SKING")

setAttributeInternal() invokes validation rules setAttributeInternal() invokes validation rules

Email attribute is set to "SKING" Email attribute is set to "SKING"

Page 44: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

44

The validateEntity() Method The validateEntity() Method

All previous examples of validation have been examples All previous examples of validation have been examples of attribute-level validation, meaning rules that apply of attribute-level validation, meaning rules that apply to a specific entity attribute, such as to a specific entity attribute, such as SalarySalary or or EmailEmail. . Some validation logic does not apply to a single Some validation logic does not apply to a single attribute, but to multiple attributes in the same row.attribute, but to multiple attributes in the same row.

Page 45: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

45

The validateEntity() Method The validateEntity() Method

For example, you might want to require that no manager (job For example, you might want to require that no manager (job title "title "MANMAN") can have a salary of less then $10,000 and that ") can have a salary of less then $10,000 and that no other employee can have a salary of $10,000 or greater. no other employee can have a salary of $10,000 or greater. This logic This logic cannotcannot be applied in setter methods for the be applied in setter methods for the following reasons:following reasons:

• For For SalarySalary alone, because it has to be applied when the alone, because it has to be applied when the users enter or change an employee's users enter or change an employee's JobIdJobId..

• For For JobIdJobId alone, because it has to be applied when users alone, because it has to be applied when users enter or change an employee's enter or change an employee's SalarySalary..

• In both setter methods, because it will be impossible to In both setter methods, because it will be impossible to promote an employee to manager. If you try to promote promote an employee to manager. If you try to promote the employee first, the employee first, setJobId()setJobId() will throw an exception will throw an exception because the salary is too low, and if you try to give the because the salary is too low, and if you try to give the employee a raise first, employee a raise first, setSalary()setSalary() will throw an will throw an exception because the employee is not yet a manager. exception because the employee is not yet a manager.

Page 46: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

46

The validateEntity() Method The validateEntity() Method

This kind of rule requires This kind of rule requires entity-levelentity-level validation - a rule validation - a rule that applies to an entire row, rather than to a single that applies to an entire row, rather than to a single attribute.attribute.

Entity-levelEntity-level validation is implemented by overriding the validation is implemented by overriding the method method EntityImpl.validateEntity()EntityImpl.validateEntity(). This method is . This method is called whenever an instance of the entity object class loses called whenever an instance of the entity object class loses currency (whenever the client is done looking at a currency (whenever the client is done looking at a particular row). If particular row). If validateEntity()validateEntity() throws an exception, throws an exception, the entity object will be prevented from losing currency. the entity object will be prevented from losing currency. The Business Component Browser, or any other client, will The Business Component Browser, or any other client, will meet an exception when it tries to scroll off the row.meet an exception when it tries to scroll off the row.

The The validateEntity()validateEntity() methodmethod is also called when a client is also called when a client attempts to commit a transaction. attempts to commit a transaction.

Page 47: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

47

The validateEntity() Method The validateEntity() Method

This will generate code like the following in the entity This will generate code like the following in the entity object's Java file:object's Java file:

The call to The call to super.validateEntity()super.validateEntity() should always be should always be kept, so that the entity object class will continue to kept, so that the entity object class will continue to exhibit exhibit EntityImplEntityImpl's default behavior in addition to 's default behavior in addition to any modifications made.any modifications made.

protected void validateEntity(){ super.validateEntity();}

Page 48: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

48

The validateEntity() Method The validateEntity() Method Put any business logic after that call. For example, the code below in Put any business logic after that call. For example, the code below in EmployeeImplEmployeeImpl would implement the manager-minimum-salary rule: would implement the manager-minimum-salary rule:

Just like the Just like the validate()validate() method in validation domains, method in validation domains, validateEntity()validateEntity() needs to do something (throw an exception) if the validation fails. needs to do something (throw an exception) if the validation fails.

protected void validateEntity() throws oracle.jbo.JboException { super.validateEntity(); if (getJobId().endswith("MAN") { if (getSalary().intValue() < 10000) { throw new oracle.jbo.JboException( "Managers must have a salary of at least 10000."); } } else { if (getSalary.intValue() > 9999) { throw new oracle.jbo.Exception( "Non-managers cannot have a salary more than 9999."); } }}

Page 49: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

49

Hands-on Practice:Add Validation to the HR Business Domain Components

Pages 303 to 314

Page 50: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

50

Adding Default Values to Entity Adding Default Values to Entity Attributes Attributes

The previous examples of business logic where triggered The previous examples of business logic where triggered when an entity object is set, its instance loses currency, or when an entity object is set, its instance loses currency, or when a transaction is committed. You might also want to when a transaction is committed. You might also want to write business logic for new rows in the database (new write business logic for new rows in the database (new entity objects) as soon as they are created.entity objects) as soon as they are created.

The most common case is The most common case is defaultingdefaulting, which means giving , which means giving an entity object a default value as soon as the row is an entity object a default value as soon as the row is created. There are two ways to implement default logic:created. There are two ways to implement default logic:

• In XMLIn XML

• In Java code for cases too complex to handle in the In Java code for cases too complex to handle in the XMLXML

These two methods are distinguished by the following:These two methods are distinguished by the following:• Static default values (value specified at design time and Static default values (value specified at design time and

always applies to the attribute) can be done in XML.always applies to the attribute) can be done in XML.

• Dynamically calculated values (attribute can have Dynamically calculated values (attribute can have different initial value in different rows) must be added different initial value in different rows) must be added to Java code. to Java code.

Page 51: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

51

Static Default Values Static Default Values The ADF BC framework stores static default values as The ADF BC framework stores static default values as XML attributes, which can be set using the XML attributes, which can be set using the DefaultDefault field in the field in the Attribute EditorAttribute Editor as shown below: as shown below:

Page 52: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

52

Static Default Values Static Default Values The ADF BC framework stores static default values as XML The ADF BC framework stores static default values as XML attributes, which can be set usingattributes, which can be set using the the DefaultDefault field in the field in the Attribute EditorAttribute Editor as shown below: as shown below:

This method can be used to set default values for any class with a String representation: String, Number, Date, Boolean, and so on, or any validation domain based on one of these classes.

Page 53: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

53

Dynamically Calculated Default Dynamically Calculated Default Values Values

Some attributes should be automatically set, but not to the same Some attributes should be automatically set, but not to the same value every time. To dynamically assign default values, Java code value every time. To dynamically assign default values, Java code must be used. This is done by overriding the method must be used. This is done by overriding the method EntityImpl.create()EntityImpl.create(), which is called whenever a new entity , which is called whenever a new entity object instance is created.object instance is created.You can generate a stub to override the You can generate a stub to override the create()create() method by method by selecting the selecting the CreateCreate MethodMethod checkbox on the checkbox on the JavaJava page of the page of the Entity Object WizardEntity Object Wizard shown below. shown below.

Page 54: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

54

Dynamically Calculated Default Dynamically Calculated Default Values Values

The The create()create() stub begins with a call to stub begins with a call to super.create()super.create(), , which you should keep. After this call, add any logic which you should keep. After this call, add any logic necessary to calculate and set defaults.necessary to calculate and set defaults.

For example, the following causes an employee's hire For example, the following causes an employee's hire date to default to the date they where added to the date to default to the date they where added to the database: database: protected void create( AttributeList attributeList ){ super.create( attributeList ); Date currDate = new Date( Date.getCurrentDate() ); setHireDate( currDate );}

Do not delete this call. It must be first

Page 55: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

55

The SequenceImpl Class and the The SequenceImpl Class and the DBSequence DomainDBSequence Domain

A common reason to dynamically calculate a default A common reason to dynamically calculate a default value is to populate attributes in successive rows with a value is to populate attributes in successive rows with a series of sequential numbers. The BC4J framework series of sequential numbers. The BC4J framework contains the contains the oracle.jbo.server.SequenceImploracle.jbo.server.SequenceImpl class class that wraps Oracle database sequences for use in the that wraps Oracle database sequences for use in the Java world. Java world. Its constructor requires two arguments:Its constructor requires two arguments:

• The name of the sequenceThe name of the sequence

• A database transaction (so ADF BC knows where A database transaction (so ADF BC knows where the sequence is)the sequence is)

The The EntityImplEntityImpl class provides a method called class provides a method called getDBTransaction()getDBTransaction() that returns the current that returns the current transaction. After calling transaction. After calling getDBTransaction()getDBTransaction(), you , you can increment the sequence and extract the next value can increment the sequence and extract the next value into a into a NumberNumber using the using the getSequenceNumber()getSequenceNumber() method. method.

Page 56: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

56

The SequenceImpl Class and the The SequenceImpl Class and the DBSequence DomainDBSequence Domain

Instead of dynamically obtaining the attribute in Java, Instead of dynamically obtaining the attribute in Java, you can put a trigger in the database to update the you can put a trigger in the database to update the attribute's table column. The attribute should be of the attribute's table column. The attribute should be of the type type DBSequenceDBSequence if this is done. if this is done. DBSequenceDBSequence maintains a temporary unique value in ADF BC cache maintains a temporary unique value in ADF BC cache until the data is posted.until the data is posted.

The advantage of The advantage of DBSequenceDBSequence over coding with over coding with SequenceImplSequenceImpl is that it does not waste sequence is that it does not waste sequence numbers in transactions that are rolled back before numbers in transactions that are rolled back before they are posted.they are posted.

But, But, DBSequenceDBSequence only works if the database has a only works if the database has a trigger to populate the attribute. trigger to populate the attribute. SequenceImplSequenceImpl populates the attribute at the Java level. . populates the attribute at the Java level. .

Page 57: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

57

Calculated Transient Attributes Calculated Transient Attributes Business rules can also be used to calculate values form Business rules can also be used to calculate values form transient attributes. Transient attributes exist only in the transient attributes. Transient attributes exist only in the entity object, and do not correspond to any database entity object, and do not correspond to any database column. Their most common use is to hold values calculated column. Their most common use is to hold values calculated from other attributes.from other attributes.

The attribute must be calculated, the first time, in its getter The attribute must be calculated, the first time, in its getter method. Your code should make sure the attribute is not method. Your code should make sure the attribute is not null (it has already been calculated), and, if it is null, null (it has already been calculated), and, if it is null, calculate it. It should both set the attribute to the calculated calculate it. It should both set the attribute to the calculated value and return that value.value and return that value.

Usually when the value of a calculated attribute is set, you Usually when the value of a calculated attribute is set, you should do so by using the method should do so by using the method EntityImpl.populateAttribute()EntityImpl.populateAttribute(). This method works like . This method works like the the setAttributeInternal()setAttributeInternal() method, with two exceptions: method, with two exceptions:

• It bypasses all validation, including XML validation It bypasses all validation, including XML validation rules.rules.

• It does not mark the entity object instance as changed It does not mark the entity object instance as changed (important for calculated values).(important for calculated values).

Page 58: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

58

Calculated Transient Attributes Calculated Transient Attributes Why use Why use populateAttribute()populateAttribute()? ?

The setAttributeInternal() method marks the entity object instance changed. When data is later posted to the database, BC4J will only attempt to post the rows marked as changed (posting the other rows wastes time). If the setAttribute() or setAttributeInternal() methods are used to calculate transient attributes, every entity instance with a calculated attribute will be marked as changed, and therefore posted to the database.

However, if the only change you have made to an instance is to calculate a transient attribute, there is generally no posting to be done. An application will save network and database resources by using populateAttribute() so that the row is NOT posted.

The setAttributeInternal() method marks the entity object instance changed. When data is later posted to the database, BC4J will only attempt to post the rows marked as changed (posting the other rows wastes time). If the setAttribute() or setAttributeInternal() methods are used to calculate transient attributes, every entity instance with a calculated attribute will be marked as changed, and therefore posted to the database.

However, if the only change you have made to an instance is to calculate a transient attribute, there is generally no posting to be done. An application will save network and database resources by using populateAttribute() so that the row is NOT posted.

You need to make sure the calculation stays up to date. Do this by putting code that sets the transient attribute to null in the setter method of any attribute this attribute depends on. For example, if the calculation depends on JobId, add code to setJobId() to set the calculated attribute to null every time JobId is changed. The next time the transient attribute is requested, it will be recalculated (because it is null).

Page 59: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

59

Using Associations in Business Rules Using Associations in Business Rules Sometimes business rules do not apply to a specific Sometimes business rules do not apply to a specific attribute, but to relationships between entities. These attribute, but to relationships between entities. These relationships were covered in Chapter 9, and are relationships were covered in Chapter 9, and are implemented by associations. Using associations allows implemented by associations. Using associations allows implementation of cross-entity business rules.implementation of cross-entity business rules.

The creation of an association creates accessors in the The creation of an association creates accessors in the entity object classes at each end. Using these accessors entity object classes at each end. Using these accessors from a particular entity object instance allows you to from a particular entity object instance allows you to access the related entity object instances at the other access the related entity object instances at the other end.end.

Page 60: 1 CHAPTER 10 More Complex Business Rules. 2 More Complex Business Rules Entity objects can do more than just be representations of data. They can also.

60

Hands-on Practice:Add More Business Rules to the HR Business Domain ComponentsPages 322 to 328


Recommended