|
Oracle® Containers for J2EE Enterprise JavaBeans Developer's Guide
10g Release 3 (10.1.3) B14428-01 |
|
![]() Previous |
![]() Next |
An entity bean is an EJB 2.1 EJB component that manages persistent data, performs complex business logic, potentially uses several dependent Java objects, and can be uniquely identified by a primary key ("What is a CMP Entity Bean Primary Key?" or "What is a BMP Entity Bean Primary Key?").
Entity beans persist business data using one of the two following methods:
Automatically by the container using a container-managed persistent (CMP) entity bean (see "What is an EJB 2.1 CMP Entity Bean?")
Programmatically through methods implemented in a bean-managed persistent (BMP) entity bean (see "What is an EJB 2.1 BMP Entity Bean?"). These methods use JDBC, SQLJ, or a persistence framework (such as TopLink) to manage persistence.
For information on choosing between CMP and BMP architectures, see "When do you use Bean-Managed versus Container-Managed Persistence?".
Entity beans are persistent because their data is stored persistently in some form of data storage system, such as a database: they do survive a server crash, failover, or a network failure. When an entity bean is re-instantiated, the state of the previous instance is automatically restored. OC4J manages this state if the entity bean must be removed from memory (see "When Does Entity Bean Passivation Occur?").
An entity bean models a business entity or models multiple actions within a business process. Entity beans are often used to facilitate business services that involve data and computations on that data. For example, an application developer might implement an entity bean to retrieve and perform computation on items within a purchase order. Your entity bean can manage multiple, dependent, persistent objects in performing its tasks.
A common design pattern pairs entity beans with a session bean that acts as the client interface. The entity bean functions as a coarse-grained object that encapsulates functionality and represents persistent data and relationships to dependent (typically find-grained) objects. Thus, you decouple the client from the data so that if the data changes, the client is not affected. For efficiency, the session bean can be collocated with entity beans and can coordinate between multiple entity beans through their local interfaces. This is known as a session facade design. See the http://java.sun.com Web site for more information on session facade design.
An entity bean can aggregate objects together and effectively persist data and related objects using container transactional, security, and concurrency services.
This section describes:
For more information, see "Implementing an EJB 2.1 Entity Bean".
When you choose to have the container manage your persistent data for an entity bean, you define a container-managed persistence (CMP) entity bean. A CMP entity bean class is an abstract class (the container provides the implementation class that is used at runtime) whose persistent data is specified as container-managed persistence fields (see "What are Container-Managed Persistence Fields?") for simple data or as container-managed relationship fields (see "What are Container-Managed Relationship Fields?") for relationships with other CMP entity beans. In this case, you do not have to implement some of the callback methods to manage persistence for your bean's data (see "What is the CMP Entity Bean Lifecycle?"), because the container stores and reloads your persistent data to and from the database. When you use container-managed persistence, the container invokes a persistence manager class that provides the persistence management business logic. OC4J uses the TopLink persistence manager by default. In addition, you do not have to provide management for the primary key (see "What is a CMP Entity Bean Primary Key?"): the container provides this key for the bean.
For more information, see "Implementing an EJB 2.1 CMP Entity Bean".
A container-managed persistence field is a state-field that represents data that must be persisted to a database.
By specifying a CMP field, you are instructing OC4J to take responsibility for ensuring that the field's value is persisted to the database. All other fields in the CMP entity bean are considered non-persistent (transient).
Using EJB 2.1, you must explicitly specify CMP fields (see "Configuring an EJB 2.1 CMP Entity Bean Container-Managed Persistence Field").
A container-managed relationship field is an association-field that represents a persistent relationship to one or more other CMP entity beans. For example, in an order management application the OrderEJB might be related to a collection of LineItemEJB beans and to a single CustomerEJB bean.
By specifying a CMR field, you are instructing OC4J to take responsiblity for ensuring that a reference to one or more related CMP entity beans is persisted to the database. For this reason, a relationship between CMP entity beans is often referred to as container-managed relationship (CMR) or a mapping from one CMP entity bean to another.
A container-managed relationship has the following characteristics:
Multiplicity - There are four types of multiplicities all of which are supported by Oracle Application Server:
Directionality - The direction of a relationship may be either bi-directional or unidirectional. In a bi-directional relationship, each entity bean has a relationship field that refers to the other bean. Through the relationship field, an entity bean's code can access its related object. If an entity bean has a relative field, then we often say that it "knows" about its related object. For example, if an ProjectEJB bean knows what TaskEJB beans it has and if each TaskEJB bean knows what ProjectEJB bean it belongs to, then they have a bi-directional relationship. In a unidirectional relationship, only one entity bean has a relationship field that refers to the other. Oracle Application Server supports both unidirectional and bi-directional relationships between EJBs.
EJB QL query support - EJB QL queries often navigate across relationships. The direction of a relationship determines whether a query can navigate from one bean to another. With OC4J, EJB QL queries can traverse CMP Relationships with any type of multiplicity and with both unidirectional and bi-directional relationships.
For more information, see:
Table 1-11 lists the EJB 2.1 lifecycle methods, as specified in the javax.ejb.EntityBean interface, that a CMP entity bean must implement. For EJB 2.1 CMP entity beans, you must at the least provide an empty implementation for all callback methods.
Table 1-11 Lifecycle Methods for an EJB 2.1 CMP Entity Bean
Each entity bean instance has a primary key that uniquely identifies it from other instances. You must declare the primary key (or the fields contained within a complex primary key) as a container-managed persistent field in the deployment descriptor.
All fields within the primary key are restricted to:
primitive object types
serializable types
types that can be mapped to SQL types
You can define a primary key in one of the following ways:
Define a simple primary key made up of a single, well-known serializable Java primitive or object type. The primary key variable that is declared within the bean class must be declared as public (see "Configuring an EJB 2.1 CMP Entity Bean Primary Key Field").
Define a composite primary key class made up of one or more well-known serializable Java primitive and/or object types within a <name>PK class that is serializable (see "Configuring an EJB 2.1 CMP Entity Bean Composite Primary Key Class").
You can assign primary key values yourself, or more typically, you can create an auto-generated primary key (see "Configuring EJB 2.1 CMP Entity Bean Automatic Primary Key Generation").
|
Note: Once the primary key for an entity bean has been set, the EJB 2.1 specification forbids you from attempting to change it. Therefore, do not expose the primary key set methods in an entity bean component interface. |
For more information, see "Configuring an EJB 2.1 CMP Entity Bean Primary Key".
When you choose to manage your persistent data for an entity bean yourself, you define a bean-managed persistence (BMP) entity bean. A BMP entity bean class is a concrete class (you provide the implementation that is used at runtime) whose persistent data is specified as bean-managed persistence fields (see "What are Bean-Managed Persistence Fields?") for simple data or as bean-managed relationship fields (see "What are Bean-Managed Relationship Fields?") for relationships with other BMP entity beans. In this case, you must implement all of the callback methods to manage persistence for your bean's data, including storing and reloading your persistent data to and from the database (see "What is the BMP Entity Bean Lifecycle?"). When you use bean-managed persistence, you must supply the code that provides the persistence management business logic. In addition, you must provide management for the primary key (see "What is a BMP Entity Bean Primary Key?").
You can specify a BMP entity bean as read-only (see "Configuring a Read-Only BMP Entity Bean") and take advantage of the optimizations that OC4J provides read-only BMP entity beans depending on the commit option you choose (see "What are Entity Bean Commit Options?")
For more information, see "Implementing an EJB 2.1 BMP Entity Bean".
With bean-managed persistence, the code that you write determines what BMP entity bean fields are persistent.
With bean-managed persistence, the code that you write implements the relationships between BMP entity beans.
Table 1-12 lists the lifecycle methods, as specified in the javax.ejb.EntityBean interface, that a BMP entity bean must implement.
For a BMP entity bean, you must provide a complete implementation of all lifecycle methods.
Table 1-12 EJB Lifecycle Methods for a BMP Entity Bean
For more information, see "Configuring a Lifecycle Callback Method for an EJB 2.1 BMP Entity Bean".
An entity bean primary key is a uniquely identifiable value that distinguishes one instance of a particular type of entity bean class from another. Each entity bean has a persistent identity associated with it. That is, the entity bean contains a unique identity that can be retrieved if you have the primary key—given the primary key, a client can retrieve the entity bean. If the bean is not available, the container instantiates the bean and repopulates the persistent data for you.
The type for the unique key is defined by the bean provider.
All fields within the primary key are restricted to:
primitive object types
serializable types
types that can be mapped to SQL types
You can define a primary key in one of the following ways:
Define the type of the primary key as a serializable object within a <name>PK class that is serializable.
In either case, for a BMP entity bean, you create the primary key in the ejbCreate method.
OC4J maintains a javax.ejb.EntityContext for each EJB 2.1 CMP or BMP entity bean instance and makes this entity context available to the beans. The bean may use the methods in the entity context to make callback requests to the container.
In addition, you can use the methods inherited from EJBContext (see "What is EJB Context?").
For more information, see:
OC4J and the TopLink persistence manager use a combination of transaction isolation (see "Transaction Isolation") and concurrency mode (see "Concurrency (Locking) Mode") to avoid database resource contention and to permit concurrent access to database tables.
The degree to which concurrent (parallel) transactions on the same data are allowed to interact is determined by the level of transaction isolation configured. ANSI/SQL defines four levels of database transaction isolation as shown in Table 1-13. Each offers a trade-off between performance and resistance from the following unwanted actions:
Dirty read: a transaction reads uncommitted data written by a concurrent transaction.
Non repeatable read: a transaction rereads data and finds it has been modified by some other transaction that was committed after the initial read operation.
Phantom read: a transaction re executes a query and the returned data has changed due to some other transaction that was committed after the initial read operation.
Table 1-13 Transaction Isolation Levels
| Transaction Isolation Level | Dirty Read | Nonrepeatable Read | Phantom Read |
|---|---|---|---|
|
Read Uncommitted |
Yes |
Yes |
Yes |
|
Read Committed |
No |
Yes |
Yes |
|
Repeatable Read |
No |
No |
Yes |
|
Serializable |
No |
No |
No |
By default, OC4J and the TopLink persistence manager provide read-committed transaction isolation.
Using a TopLink persistence manager customization file (see "Customizing the TopLink Persistence Manager"), you can configure the transaction isolation mode. For more information, see:
"Unit of Work Transaction Isolation" in the Oracle TopLink Developer's Guide
"Database Transaction Isolation Levels" in the Oracle TopLink Developer's Guide
OC4J also provides concurrency modes for handling resource contention and parallel execution within container-managed persistence (CMP) entity beans.
Bean-managed persistence entity beans manage the resource locking within the bean implementation themselves.
CMP entity bean concurrency modes include:
Optimistic Locking: Multiple users have read access to the data. When a user attempts to make a change, the application checks to ensure the data has not changed since the user read the data
By default, the TopLink persistence manager enforces optimistic locking by using a numeric version field (also known as a write-lock field) that TopLink updates each time an object change is committed.
TopLink caches the value of this version field as it reads an object from the data source. When the client attempts to write the object, TopLink compares the cached version value with the current version value in the data source in the following way:
If the values are the same, TopLink updates the version field in the object and commits the changes to the data source.
If the values are different, the write operation is disallowed because another client must have updated the object since this client initially read it.
Pessimistic Locking: The first user who accesses the data with the purpose of updating it locks the data until completing the update. This manages resource contention and does not allow parallel execution. Only one user at a time is allowed to execute the entity bean at a single time.
Read-only: Multiple users can execute the entity bean in parallel. The container does not allow any updates to the bean's state.
These concurrency modes are defined per bean and apply on the transaction boundaries.
By default, OC4J and the TopLink persistence manager use optimistic locking and all CMP entity beans are not read-only.
Using a TopLink persistence manager customization file (see "Customizing the TopLink Persistence Manager"), you can configure the concurrency mode on a per-CMP EJB basis. For more information, see:
"Locking" in the Oracle TopLink Developer's Guide
"Configuring Locking Policy" in the Oracle TopLink Developer's Guide
"Configuring Read-Only Descriptors" in the Oracle TopLink Developer's Guide
Entity bean passivation applies only to EJB 2.1 CMP entity beans.
OC4J passivates an instance when the container decides to disassociate the instance from an entity object identity, and to put the instance back into the pool of available instances. OC4J calls the instance's ejbPassivate method to give the instance the chance to release any resources (typically allocated in the ejbActivate method) that should not be held while the instance is in the pool. This method executes with an unspecified transaction context. The entity bean must not attempt to access its persistent state or relationships using the accessor methods during this method.
Commit options determine entity bean instance state at transaction commit time and offer the flexibility to allow OC4J to optimize certain application conditions.
Table 1-14 lists the commit options as defined by the EJB 2.1 specification and indicates which are supported by OC4J.
Table 1-14 OC4J Support for Entity Bean Commit Options
| Commit Option | OC4J Support | Description | Instance state written to database? | Instance stays ready | Instance state remains valid | Advantages | Disadvantages |
|---|---|---|---|---|---|---|---|
|
A |
Cached bean: At the end of the transaction, the instance stays in the ready state (cached) and the instance state is valid ( |
|
|
|
Least database access. |
Exclusive access required. Multiple threads share same bean instance (poor performance). |
|
|
B |
|
Stale bean: At the end of the transaction, the instance stays in the ready state (cached) but the instance state is not valid: |
|
|
|
Moderate database access. Allows concurrent requests. |
Overhead of multiple bean instances representing the same data. Each transaction calls |
|
C |
Pooled bean: At the end of the transaction, neither the instance nor its state is valid (instance will be passivated and returned to the pool). Every client call causes an |
|
|
|
Best scalability. Allows concurrent requests. Need not hold on to connections. |
Most database access (every business method call). No caching. |
Footnote 1 BMP entity beans only (see "Commit Options and BMP Applications").
Footnote 2 CMP entity beans only (see "Commit Options and CMP Applications").
For an EJB 2.1 CMP application deployed to OC4J using the TopLink persistence manager, by default, OC4J uses TopLink configuration to approximate commit option C. This option provides the best performance and scalability over the widest range of applications.
OC4J EJB 2.1 CMP conforms to option C in terms of lifecycle method calls. However, the TopLink persistence manager introduces the following innovations:
It provides caching using the TopLink cache.
It does not synchronize the instance with the data source at the begining of every transaction if the instance is already in the TopLink cache.
You can use locking or synchronization with a TopLink pessimistic or optimistic locking policy to handle conccurent services to the same bean. This provides the best performance for conccurent access of the same instance while guaranteeing an instance is not updated with stale data.
For more information on making fine-grained TopLink configuration changes, see:
"Configuring Locking Policy" in the Oracle TopLink Developer's Guide
For an EJB 2.1 BMP application deployed to OC4J, you can configure commit option A (see "Configuring BMP Commit Options").
When you configure a BMP entity bean as read-only, OC4J uses a special case of commit option A to improve performance. In this case, OC4J caches the instance and and does not update the instance or call ejbStore when the transaction commits. For more information, see "Configuring a Read-Only BMP Entity Bean".
You can use BMP commit option A and read-only BMP entity beans independently (that is, you can configure a BMP entity bean with commit option A without using read-only and you can use read-only without configuring a BMP entity bean with commit option A).
To query for an EJB 2.1 entity bean instance, you use a finder or select method (see "Understanding Finder Methods" and "Understanding Select Methods").
In either case, you express your selection criteria using an appropriate query syntax (see "Understanding EJB Query Syntax").
For more information, see "Using EJB 2.1 Query API".
Table 1-15 summarizes the types of query syntax you can use to define EJB queries.
Table 1-15 OC4J EJB Query Syntax Support
| Query Syntax | See Also |
|---|---|
|
EJB QL |
"Understanding EJB Query Syntax" |
|
TopLink |
"Understanding TopLink Query Syntax" |
|
Predefined Finder |
|
|
Default Finder |
|
|
Custom Finder |
|
|
Custom Select |
"Custom TopLink Select Methods" |
|
Native SQL |
"Understanding Native SQL Query Syntax" |
Oracle recommends EJB QL because it is both portable and optimizable.
EJB QL is a specification language used to define semantics of finder and select methods (see "Understanding Finder Methods" and "Understanding Select Methods") in a portable and optimizable format. You ensure that an EJB QL statement is associated with each finder and select method.
Although similar to SQL, EJB QL offers significant advantages over native SQL. While SQL applies queries against tables, using column names, EJB QL applies queries against CMP entity beans, using the abstract schema name and the CMP and CMR fields of the bean within the query. The EJB QL statement retains the object terminology. The container translates the EJB QL statement to the appropriate database SQL statement when the application is deployed. Thus, the container is responsible for converting the entity bean name, CMP field names, and CMR field names to the appropriate database tables and column names. EJB QL is portable to all databases supported by OC4J.
In EJB 2.1, EJB QL is a subset of SQL92, that includes extensions that allow navigation over the relationships defined in an entity bean's abstract schema. The abstract schema is part of an entity bean's deployment descriptor and defines the bean's persistent fields and relationships. The term "abstract" distinguishes this schema from the physical schema of the underlying data store. The abstract schema name is referenced by EJB QL queries since the scope of an EJB QL query spans the abstract schemas of related entity beans that are packaged in the same EJB JAR file.
For an entity bean with container-managed persistence, an EJB QL query must be defined for every finder method (except findByPrimaryKey). Using OC4J with the TopLink persistence manager, you can take advantage of predefined and default finder and select methods (see "TopLink Finders" and "Custom TopLink Select Methods"). The EJB QL query determines the query that is executed by the EJB container when the finder or select method is invoked.
Oracle Application Server provides complete support for EJB QL with the following important features:
Automatic Code Generation: EJB QL queries are defined in the deployment descriptor of the entity bean. When the EJBs are deployed to Oracle Application Server, the container automatically translates the queries into the SQL dialect of the target data store. Because of this translation, entity beans with container-managed persistence are portable -- their code is not tied to a specific type of data store.
Optimized SQL Code Generation: Further, in generating the SQL code, Oracle Application Server makes several optimizations such as the use of bulk SQL, batched statement dispatch, and so on to make database access efficient.
Support for Oracle and Non-Oracle Databases: Further, Oracle Application Server provides the ability to execute EJB QL against any database - Oracle, MS SQL-Server, IBM DB/2, Informix, and Sybase.
CMP with Relationships: Oracle Application Server supports EJB QL for both single entity beans and also with entity beans that have relationships, with support for any type of multiplicity and directionality.
Using EJB 2.1, OC4J provides proprietary EJB QL extensions to support SQRT and date, time, and timestamp options not available in EJB 2.1 (see "OC4J EJB 2.1 EJB QL Extensions").
In this release, because TopLink is the default persistence manager (see "TopLink Persistence Manager"), you can express selection criteria for an EJB 2.1 finder or select method using the TopLink query and expressions framework. This EJB QL alternative offers numerous advantages (see "Advantages of TopLink Queries and Expressions").
You can use the TopLink Workbench to customize your ejb-jar.xml file to create advanced finder and select methods using the TopLink query and expression framework.
You also can take advantage of the predefined and default finders and select methods that the TopLink persistence manager provides (see "TopLink Finders" and "Custom TopLink Select Methods").
For more information, see:
"Understanding TopLink Queries" in the Oracle TopLink Developer's Guide
"Understanding TopLink Expressions" in the Oracle TopLink Developer's Guide.
"Configuring Named Queries at the Descriptor Level" in the Oracle TopLink Developer's Guide
"Using EJB Finders" in the Oracle TopLink Developer's Guide
"Working with the ejb-jar.xml File" in the Oracle TopLink Developer's Guide
Advantages of TopLink Queries and Expressions
Using the TopLink expressions framework, you can specify query search criteria based on your domain object model.
Expressions offer the following advantages over SQL when you access a database:
Expressions are easier to maintain because, like EJB QL, the database is abstracted.
Changes to descriptors or database tables do not affect the querying structures in the application.
Expressions enhance readability by standardizing the Query interface so that it looks similar to traditional Java calling conventions. For example, the Java code required to get the street name from the Address object of the Employee class looks like this:
emp.getAddress().getStreet().equals("Meadowlands");
The expression to get the same information is similar:
emp.get("address").get("street").equal("Meadowlands");
Expressions allow read queries to transparently query between two classes that share a relationship. If these classes are stored in multiple tables in the database, TopLink automatically generates the appropriate join statements to return information from both tables.
Expressions simplify complex operations. For example, the following Java code retrieves all Employees that live on "Meadowlands" whose salary is greater than 10,000:
ExpressionBuilder emp = new ExpressionBuilder();
Expression exp = emp.get("address").get("street").equal("Meadowlands");
Vector employees = session.readAllObjects(Employee.class,
exp.and(emp.get("salary").greaterThan(10000)));
TopLink automatically generates the appropriate SQL from that code:
SELECT t0.VERSION, t0.ADDR_ID, t0.F_NAME, t0.EMP_ID, t0.L_NAME, t0.MANAGER_ID, t0.END_DATE, t0.START_DATE, t0.GENDER, t0.START_TIME, t0.END_TIME,t0.SALARY FROM EMPLOYEE t0, ADDRESS t1 WHERE (((t1.STREET = 'Meadowlands')AND (t0.SALARY > 10000)) AND (t1.ADDRESS_ID = t0.ADDR_ID))
In this release, the TopLink persistence manager takes the query syntax you specify ("Understanding EJB QL Query Syntax" or "Understanding TopLink Query Syntax") and generates Sequential Query Language (SQL) native to your underlying relational database.
EJB QL is the preferred syntax because it is portable and optimizable.
Native SQL is appropriate for taking advantage of advanced query features of your underlying relational database that EJB QL does not support.
Using EJB 2.1 and the TopLink query syntax, you can use:
default finders that take a native SQL string (see "Default TopLink Finders")
custom finder or select methods that use native SQL calls (see "TopLink Finders" and "Custom TopLink Select Methods")
To use native SQL otherwise, you must use straight JDBC calls.
A finder method is an EJB method the name of which begins with find that you define in the Home interface of an EJB (see or "Implementing the EJB 2.1 Home Interfaces") and associate with a query to return one or more instances of that EJB type. At deployment time, OC4J provides an implementation of this method that executes the associated query.
Finder methods are the means by which clients retrieve EJB 2.1 CMP entity beans. Using EJB 2.1, you can:
Expose any of the predefined and default finders that OC4J and the TopLink persistence manager provide to all CMP entity beans (see "Predefined TopLink Finders" and "Default TopLink Finders").
Define custom EJB QL finders (see "Implementing an EJB 2.1 EJB QL Finder Method") and custom TopLink finders (see "Custom TopLink Finders").
A finder that returns a single EJB instance has a return type of that EJB instance.
A finder that returns more than one EJB instance has a return type of Collection. If no matches are found, an empty Collection is returned. To ensure that no duplicates are returned, specify the DISTINCT keyword in the associated EJB query.
All finders throw FinderException.
At the very least, you must expose the findByPrimaryKey finder method to retrieve a reference for each entity bean using its primary key.
The TopLink persistence manager provides OC4J entity beans with a variety of predefined (see "Predefined TopLink Finders") and default (see "Default TopLink Finders") finders. You can expose these finders to your clients as you would for any other finder. You do not need to specify a corresponding query. You can also create custom TopLink finders (see "Custom TopLink Finders").
Predefined TopLink Finders
Table 1-16 lists the predefined finders you can expose for EJB 2.1 CMP entity beans. The TopLink persistence manager reserves the method names listed in Table 1-16.
Table 1-16 Predefined TopLink CMP Finders
| Method | Arguments | Return |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Component interface |
|
|
|
|
|
|
|
Component interface |
|
|
|
|
|
|
|
Component interface |
|
|
|
Footnote 1 Depending on whether or not the finder is defined in the home or component interface.
Example 1-4 shows an EJBHome that defines two predefined finders (findByPrimaryKey and findManyBySQL). TopLink will provide the query implementation for these finders.
Example 1-3 Specifying Predefined TopLink Finders
public interface EmpBeanHome extends EJBHome
{
public EmpBean create(Integer empNo, String empName) throws CreateException;
/**
* Finder methods. These are implemented by the container. We can
* customize the functionality of these methods in the deployment
* descriptor through EJB-QL.
**/
// Predefined Finders: <query> element in ejb-jar.xml not required
public Topic findByPrimaryKey(Integer key) throws FinderException;
public Collection findManyBySQL(String sql, Vector args) throws FinderException
}
Default TopLink Finders
For each finder method defined in the home interface of an entity bean whose name matches findBy<CMP-FIELD-NAME> where <CMP-FIELD-NAME> is the name of a persistent field on the bean, TopLink generates a finder implementation including a TopLink query that uses the TopLink expressions framework. If the return type is a single bean type, TopLink creates a oracle.toplink.queryframework.ReadObjectQuery; if the return type is Collection, TopLink creates a oracle.toplink.queryframework.ReadAllQuery. You can expose these finders to your clients as you would for any other finder. You do not need to specify a corresponding query.
Example 1-4 shows an EJBHome that defines a default finder (findByEmpNo). TopLink will provide the query implementation for this finder.
Example 1-4 Specifying Default TopLink Finders
public interface EmpBeanHome extends EJBHome
{
public EmpBean create(Integer empNo, String empName) throws CreateException;
/**
* Finder methods. These are implemented by the container. We can
* customize the functionality of these methods in the deployment
* descriptor through EJB-QL.
**/
// Default Finder: <query> element in ejb-jar.xml not required
public Topic findByEmpNo(Integer empNo);
}
Custom TopLink Finders
You can take advantage of the TopLink query and expression framework to define advanced finders, including Call, DatabaseQuery, primary key, Expression, EJB QL, native SQL, and redirect finders (that delegate execution to the implementation that you define as a static method on an arbitrary helper class).
Using EJB 2.1, to create custom TopLink finders, use your existing toplink-ejb-jar.xml file with the TopLink Workbench (see "Using TopLink Workbench").
An entity bean select method is a query method intended for internal use within an EJB 2.1 CMP entity bean instance. You define a select method as an abstract method of the abstract entity bean class itself and associate an EJB QL query with it. You do not expose the select method to the client in the home or component interface. You may define zero or more select methods. The container is responsible for providing the implementation of the select method based on the EJB QL query you associate with it.
You typically call a select method within a business method to retrieve the value of a CMP field or entity bean references of container-managed relationship (CMR) fields. A select method executes in the transaction context determined by the transaction attribute of the invoking business method.
A select method has the following signature:
public abstract <ReturnType> ejbSelect<MethodName>(...) throws FinderException
It must be declared as public and abstract.
The return type must conform to the select method return type rules (see "What Type Can My Select Method Return?").
The method name must start with ejbSelect.
The method must throw javax.ejb.FinderException and may also throw other application-specific exceptions as well.
Although the select method is not based on the identity of the entity bean instance on which it is invoked, it can use the primary key of an entity bean as an argument. This creates a query that is logically scoped to a particular entity bean instance.
Using EJB 2.1, you can define custom EJB QL select methods (see "Implementing an EJB 2.1 EJB QL Select Method") and you can define custom TopLink select methods (see "Custom TopLink Select Methods").
The select method return type is not restricted to the entity bean type on which the select is invoked. Instead, it can return any type corresponding to a CMP or CMR field.
Your select method must conform to the following return type rules:
All values must be returned as objects; any primitive types are wrapped in their corresponding object types (for example, a primitive int is wrapped in an Integer object).
Single object: If your select method returns only a single item, the container returns the same type as specified in your select method signature.
If multiple objects are returned, a FinderException is raised.
If no objects are found, a FinderException is raised
Multiple objects: If your select method returns multiple items, you must define the return type as a Collection.
Choose the Collection type to suit your needs. For example, a Collection may include duplicates, a Set eliminates duplicates, and a SortedSet will return an ordered Collection.
If no objects are found, an empty Collection is returned.
CMP values: If you return multiple CMP values, the container returns a Collection of objects whose type it determines from the EJB QL select statement.
CMR values: If you return multiple CMR values, then by default, the container returns a Collection of objects whose type is the local bean interface type.
You can change this to the remote bean interface with annotations or deployment XML configuration. For more information, see "Implementing an EJB 2.1 EJB QL Select Method".
Using EJB 2.1, you can create custom TopLink select methods.
Using EJB 2.1, you can take advantage of the TopLink query and expression framework to define advanced select methods that can use any of the TopLink query and expression framework features, including Call, DatabaseQuery, Expression, EJB QL, and native SQL. For more information, see "Using TopLink Workbench".