Skip Headers
Oracle® Containers for J2EE Enterprise JavaBeans Developer's Guide
10g (10.1.3.5.0)

Part Number E13981-01
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Index
Index
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
View PDF

What is an EJB 2.1 Entity Bean?

An entity bean is an EJB 2.1 enterprise bean component that manages persistent data, performs complex business logic, potentially uses several dependent Java objects, and can be uniquely identified by a primary key.

Entity beans persist business data using one of the two following methods:

For information on choosing between container-managed persistence and container-managed persistence 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, such as a database: entity beans survive a server failure, failover, or a network failure. When an entity bean is reinstantiated, 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 multiple actions within a single business process. Entity beans are often used to facilitate business services that involve data and computations on that data. For example, you 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 the following:

For more information, see "Implementing an EJB 2.1 Entity Bean".

What is an EJB 2.1 Entity Bean With Container-Managed Persistence?

When you choose to have the container manage your persistent data for an entity bean, you define an entity bean with container-managed persistence. A class of an entity bean with container-managed persistence is an abstract class (the container provides the implementation class that is used at run time), whose persistent data is specified as container-managed persistent fields (see "What are Container-Managed Persistent Fields?") for simple data, or as container-managed relationship fields (see "What are Container-Managed Relationship Fields?") for relationships with other entity beans with container-managed persistence. 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 Life Cycle of an EJB 2.1 Entity Bean With Container-Managed Persistence?"), 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 Primary Key of an Entity Bean With Container-Managed Persistence?"): the container provides this key for the bean.

For more information, see the following:

What are Container-Managed Persistent Fields?

A container-managed persistent field is a state-field that represents data that must be persisted to a database.

By specifying a container-managed persistent 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 entity bean with container-managed persistence are considered nonpersistent (transient).

Using EJB 2.1, you must explicitly specify container-managed persistent fields (see "Configuring a Container-Managed Persistent Field for an EJB 2.1 Entity Bean With Container-Managed Persistence").

What are Container-Managed Relationship Fields?

A container-managed relationship field is an association-field that represents a persistent relationship to one or more other entity beans with container-managed persistence. 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 container-managed relationship field, you are instructing OC4J to take responsiblity for ensuring that a reference to one or more related entity beans with container-managed persistence is persisted to the database. For this reason, a relationship between entity beans with container-managed persistence is often referred to as container-managed relationship or a mapping from one entity bean with container-managed persistence 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 it "knows" about its related object. For example, if an ProjectEJB bean knows what TaskEJB beans it has and if each TaskEJB bean knows to which ProjectEJB bean it belongs, 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 enterprise beans.

  • 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 container-managed relationships with any type of multiplicity and with both unidirectional and bi-directional relationships.

For more information, see the following:

What is the Life Cycle of an EJB 2.1 Entity Bean With Container-Managed Persistence?

Figure 1-6 shows the life cycle of an EJB 2.1 entity bean with container-managed persistence.

Figure 1-6 Life Cycle of EJB 2.1 Entity Bean With Container-Managed Persistence

Description of Figure 1-6 follows
Description of "Figure 1-6 Life Cycle of EJB 2.1 Entity Bean With Container-Managed Persistence"

Table 1-13 lists the EJB 2.1 enterprise bean's life cycle methods, as specified in the javax.ejb.EntityBean interface, that an entity bean with container-managed persistence must implement. For EJB 2.1 entity beans with container-managed persistence, you must at the least provide an empty implementation for all callback methods.

Table 1-13 Life Cycle Methods for an EJB 2.1 Entity Bean With Container-Managed Persistence

EJB Method Description

ejbCreate

You must implement an ejbCreate method corresponding to each create method declared in the home interface. When the client invokes the create method, the container first invokes the constructor to instantiate the object, then it invokes the corresponding ejbCreate method.

For an entity bean with container-managed persistence, use this method to initialize container-managed persistent fields.

The return type of all ejbCreate methods is the type of the bean's primary key.

Optionally, you can initialize the bean with a unique primary key and return it. If you rely on the container to create and initialize the primary key, return null.

ejbPostCreate

The container invokes this method after the environment is set. For each ejbCreate method, an ejbPostCreate method must exist with the same arguments.

For an entity bean with container-managed persistence, you can leave this implementation empty, or use your implementation to initialize parameters within or from the entity context.

ejbRemove

The container invokes this method before it ends the life of the entity bean.

For an entity bean with container-managed persistence, you can leave this implementation empty, or use your implementation to perform any required clean-up (for example, closing external resources such as file handles).

ejbStore

The container invokes this method right before a transaction commits. It saves the persistent data to an outside resource, such as a database.

For an entity bean with container-managed persistence, you can leave this implementation empty.

ejbLoad

The container invokes this method when the data should be reinitialized from the database. This normally occurs after activation of an entity bean.

For an entity bean with container-managed persistence, you can leave this implementation empty.

ejbActivate

The container calls this method directly before it activates an object that was previously passivated. Perform any necessary reaquisition of resources in this method.

ejbPassivate

The container calls this method before it passivates the object. Release any resources that can be easily re-created in ejbActivate, and save storage space. Typically, you want to release resources that cannot be passivated, such as sockets or database connections. Retrieve these resources in the ejbActivate method.


For more information, see the following:

What is a Primary Key of an Entity Bean With Container-Managed Persistence?

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 the following:

  • 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:

Typically, you rely on OC4J to assign primary key values automatically. To configure how OC4J assigns primary key values, you use TopLink persistence API. For more information, see the following:

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 a Primary Key for an EJB 2.1 Entity Bean With Container-Managed Persistence".

What is an EJB 2.1 Entity Bean With Bean-Managed Persistence?

When you choose to manage your persistent data for an entity bean yourself, you define an entity bean with bean-managed persistence. A class of an entity bean with bean-managed persistence is a concrete class (you provide the implementation that is used at run time), whose persistent data is specified as bean-managed persistent fields (see "What are Bean-Managed Persistent Fields?") for simple data, or as bean-managed relationship fields (see "What are Bean-Managed Relationship Fields?") for relationships with other entity beans with bean-managed persistence. 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 Life Cycle of an EJB 2.1 Entity Bean With Bean-Managed Persistence?"). 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 Primary Key of an Entity Bean With Bean-Managed Persistence?").

You can specify an entity bean with bean-managed persistence as read-only (see "Configuring a Read-Only Entity Bean With Bean-Managed Persistence") and take advantage of the optimizations with which OC4J provides read-only entity beans with bean-managed persistence depending on the commit option you choose (see "What are Entity Bean Commit Options?")

For more information, see the following:

What are Bean-Managed Persistent Fields?

With bean-managed persistence, the code that you write determines which fields of an entity bean with bean-managed persistence are persistent.

What are Bean-Managed Relationship Fields?

With bean-managed persistence, the code that you write implements the relationships between entity beans with bean-managed persistence.

What is the Life Cycle of an EJB 2.1 Entity Bean With Bean-Managed Persistence?

Table 1-14 lists the life cycle methods, as specified in the javax.ejb.EntityBean interface, that an entity bean with bean-managed persistence must implement.

For an entity bean with bean-managed persistence, you must provide a complete implementation of all life cycle methods.

Table 1-14 EJB Life Cycle Methods for an Entity Bean With Bean-Managed Persistence

EJB Method Description

ejbCreate

You must implement an ejbCreate method corresponding to each create method declared in the home interface. When the client invokes the create method, the container first invokes the constructor to instantiate the object, then it invokes the corresponding ejbCreate method. The ejbCreate method performs the following:

  • creates any persistent storage for its data, such as database rows;

  • initializes a unique primary key and returns it.

ejbPostCreate

The container invokes this method after the environment is set. For each ejbCreate method, an ejbPostCreate method must exist with the same arguments. This method can be used to initialize parameters within or from the entity context.

ejbRemove

The container invokes this method before it ends the life of the session object. This method can perform any required clean-up (for example, closing external resources such as file handles).

ejbStore

The container invokes this method right before a transaction commits. It saves the persistent data to an outside resource, such as a database.

ejbLoad

The container invokes this method when the data should be reinitialized from the database. This usually occurs after activation of an entity bean.

ejbActivate

The container calls this method directly before it activates an object that was previously passivated. Perform any necessary reaquisition of resources in this method.

ejbPassivate

The container calls this method before it passivates the object. Release any resources that can be easily re-created in ejbActivate, and save storage space. Typically, you want to release resources that cannot be passivated, such as sockets or database connections. Retrieve these resources in the ejbActivate method.


For more information, see the following:

What is a Primary Key of an Entity Bean With Bean-Managed Persistence?

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 the following:

  • primitive object types;

  • serializable types;

  • types that can be mapped to SQL types;

  • types that are a legal Value Type in RMI-IIOP;

  • types that provide a suitable implementation of the hashCode() and equals(Object) methods.

You can define a primary key in one of the following ways (in either case, for an entity bean with bean-managed persistence, you create the primary key in the ejbCreate method):

What is Entity Context?

OC4J maintains a javax.ejb.EntityContext for each EJB 2.1 entity bean with container-managed persistence or entity bean with bean-managed persistence 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 the following:

When Does Entity Bean Passivation Occur?

Entity bean passivation applies only to EJB 2.1 entity beans with container-managed persistence.

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.

What are Entity Bean Commit Options?

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-15 lists the commit options as defined by the EJB 2.1 specification and indicates which are supported by OC4J.

Table 1-15 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

SupportedFoot 1 

Cached bean: At the end of the transaction, the instance stays in the ready state (cached) and the instance state is valid (ejbLoad called once on activation).

Supported Supported Supported

Least database access.

Exclusive access required.

Multiple threads share same bean instance (poor performance).

B

Not Supported

Stale bean: At the end of the transaction, the instance stays in the ready state (cached) but the instance state is not valid: ejbLoad and ejbStore called for each transaction.

Supported Supported Not Supported

Moderate database access.

Allows concurrent requests.

Overhead of multiple bean instances representing the same data.

Each transaction calls ejbLoad

C

SupportedFoot 2 

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 ejbActivate, ejbLoad, then the business method, then ejbStore, and ejbPassivate.

Supported Not Supported Not Supported

Best scalability.

Allows concurrent requests.

Need not hold on to connections.

Most database access (every business method call).

No caching.


Footnote 1 Entity beans with bean-managed persistence only (see "Commit Options and BMP Applications").

Footnote 2 Entity beans with container-managed persistence only (see "Commit Options and CMP Applications").

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 life cycle 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 beginning 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 concurrent services to the same bean. This provides the best performance for concurrent 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 the following:

Commit Options and BMP Applications

For an EJB 2.1 BMP application deployed to OC4J, you can configure commit option A or C (see "Configuring Commit Options for an Entity Bean With Bean-Managed Persistence").

When you configure an entity bean with bean-managed persistence as read-only, OC4J uses a special case of commit option A to improve performance. In this case, OC4J caches the instance and does not update the instance or call ejbStore when the transaction commits. For more information, see "Configuring a Read-Only Entity Bean With Bean-Managed Persistence".

You can use BMP commit option A and read-only entity beans with bean-managed persistence independently (that is, you can configure an entity bean with bean-managed persistence with commit option A without using read-only and you can use read-only without configuring an entity bean with bean-managed persistence with commit option A).

How do you Query for an EJB 2.1 Entity Bean?

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 2.1 Query Syntax").

For more information, see "Implementing EJB 2.1 Queries".

Understanding EJB 2.1 Query Syntax

Table 1-16 summarizes the types of query syntax you can use to define EJB queries.

Table 1-16 OC4J EJB 2.1 Query Syntax Support

Query Syntax See Also

EJB QL

"Understanding EJB 2.1 Query Syntax"

TopLink

"Understanding TopLink Query Syntax"

    Predefined Finder

"Predefined TopLink Finders"

    Default Finder

"Default TopLink Finders"

    Custom Finder

"Custom TopLink Finders"

    Custom Select

"Custom TopLink Select Methods"

Native SQL

"Understanding Native SQL Query Syntax in EJB 2.1"


Oracle recommends the use of EJB QL because it is both portable and optimizable.

Understanding EJB QL Query Syntax

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 entity beans with container-managed persistence, using the abstract schema name and the container-managed persistent and relationship 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, container-managed president field names, and container-managed relationship 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 enterprise beans 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 such as 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").

Understanding TopLink Query Syntax

In this release, because TopLink is the default persistence manager (see "TopLink EJB 2.1 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 the following:

  • "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 as follows:

    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))
    

Understanding Native SQL Query Syntax in EJB 2.1

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 the following:

To use native SQL otherwise, you must use straight JDBC calls.

Understanding Finder Methods

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 entity beans with container-managed persistence. Using EJB 2.1, you can do the following:

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.

TopLink Finders

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-17 lists the predefined finders you can expose for EJB 2.1 entity beans with container-managed persistence. The TopLink persistence manager reserves the method names listed in Table 1-17.

Table 1-17 Predefined TopLink CMP Finders

Method Arguments Return

findAll

()

Collection

findManyByEJBQL

(String ejbql) (String ejbql, Vector args)

Collection

findManyByQuery

(DatabaseQuery query)(DatabaseQuery query, Vector args)

Collection

findManyBySQL

(String sql)(String sql, Vector args)

Collection

findByPrimaryKey

(Object primaryKeyObject)

EJBObject or EJBLocalObjectFoot 1 

findOneByEJBQL

(String ejbql)

Component interface

findOneByEJBQL

(String ejbql, Vector args)

EJBObject or EJBLocalObjectFootref 1

findOneByQuery

(DatabaseQuery query)

Component interface

findOneByQuery

(DatabaseQuery query, Vector args)

EJBObject or EJBLocalObjectFootref 1

findOneBySQL

(String sql)

Component interface

findOneBySQL

(String sql, Vector args)

EJBObject or EJBLocalObjectFootref 1


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. You 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. You 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").

Understanding Select Methods

An entity bean select method is a query method intended for internal use within an EJB 2.1 entity bean with container-managed persistence 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 container-managed persistent field or entity bean references of container-managed relationship 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<METHOD>(...) 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 Your 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").

What Type Can Your Select Method Return?

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 container-managed persistent or container-managed relationship field.

Your select method must conform to the following return type rules:

  • All values must be returned as Object; 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.

    • Container-managed persistent values: If you return multiple container-managed persistent values, the container returns a Collection of objects whose type it determines from the EJB QL select statement.

    • Container-managed relationship values: If you return multiple container-managed relationship 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".

Custom TopLink Select Methods

Using EJB 2.1, you can create custom TopLink select methods.

Using EJB 2.1, you can utilize 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".