Oracle® Containers for J2EE Orion CMP Developer's Guide 10g Release 3 (10.1.3.1) Part Number B28220-01 |
|
|
View PDF |
This chapter introduces the concept of an entity bean in general, and entity bean with container-managed persistence in particular.
This chapter includes information on the following topics:
Within a J2EE SDK environment, an entity bean represents a business object in a relational database. Usually, an entity bean has an underlying table in a relational database, and every instance of the bean corresponds to a row in that database.
Entity beans possess the following characteristics:
They are persistent
They allow shared access
They have primary keys
They may participate in relationships with other entity beans
For more information about entity beans, see the following:
The J2EE Tutorial at http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/EJBConcepts4.html#62950
EJB 2.0 specification at http://java.sun.com/products/ejb/docs.html
This section elaborates on the following topics specific to entity beans with container-managed persistence:
Terminologically, container-managed persistence is the process of the EJB container handling the database access required by an entity bean. That is, the bean's code does not contain SQL calls. This makes the bean's code oblivious to the underlying database. You do not have to implement some of the callback methods (see "Callback Methods") to manage persistence for your bean's data, because the container stores and reloads your persistent data to and from the database. In addition, you do not have to provide management for the primary key as the container provides this key for your bean (see "Configuring Primary Key").
In Orion entity beans with container-managed persistence, the Orion persistence manager is used by the EJB container to persist data to the database from the entity beans. See "Preface" for details on the terminology.
For more information about persistence managers, see the following:
An entity bean's deployment descriptor contains an abstract schema that defines the bean's persistent fields (see "Container-Managed Persistent Fields") and relationships (see "Container-Managed Relationships").
Note: Do not confuse the terms abstract schema and physical schema: in a relational database, a physical schema consists of tables and columns, whereas an abstract schema is a provider of the information required by the container in order to produce the data access calls. |
This section describes the following:
Persistent fields of an entity bean define the state of the bean. These fields are stored in the underlying database. The container performs an automatic synchronization of the bean's state with the database at run time. At deployment time, the container usually maps the entity bean to a database table with the persistent fields mapped to the table's columns.
Persistent fields are virtual in container-managed persistence. This means that you declare them in the abstract schema, but do not make them instance variables in your entity bean class. However, you provide getters and setters for the persistent fields in your code, similar to the following:
public abstract String getEmployeeName() throws RemoteException public abstract String getAddress() throws RemoteException public abstract void setAddress(String newAddress) throws RemoteException
The container provides the implementation of these methods.
In the preceding example, the corresponding persistence fields are employeeName
and address
.
The EJB deployment descriptor in a form of an ejb-jar.xml
file declares these fields as persistent. Each field name must be defined in a <cmp-field><field-name>
element of the deployment descriptor, similar to the following:
<entity> ... <cmp-field><field-name>employeeName</cmp-field></field-name> <cmp-field><field-name>address</cmp-field></field-name> ... </entity>
For more information on how to configure persistence fields, see "Configuring Container-Managed Persistent Fields".
For more information on how to implement entity beans, see "Implementing an EJB 2.0 Entity Bean With Container-Managed Persistence".
An entity bean may be related to other entity beans. This behavior of entity beans is similar to the behavior of tables in a relational database.
The EJB container is responsible for relationships in entity beans with container-managed persistence.
OC4J supports the following types of container-managed relationships (CMR):
One-to-one: an instance of an entity bean is related to an instance of another entity bean. For example, in a hypothetical model of a racing track with each car containing one driver, CarEJB
and DriverEJB
are in a one-to-one relationship.
One-to-many: an instance of an entity bean may be related to more than one instance of another entity bean. Reusing the racing track example from the previous item, the racing track accommodates multiple competing cars, making RacingTrackEJB
have a one-to-many relationships with CarEJB
.
Many-to-one: multiple instances of an entity bean may be related to one instance of another entity bean. For example, reversing the one-to-many racing track scenario, many cars compete in a single racing track, therefore CarEJB
has a many-to-one relationship with RacingTrackEJB
.
Many-to-many: instances of an entity bean may be related to multiple instances of each other. For example, on a racing track, each car can be served by multiple mechanics, and every mechanic serves more than one car. This makes CarEJB
and MechanicEJB
have a many-to-many relationship.
An entity bean represents a "one" side of a relationship by the local bean object, whereas the "many" side is represented using a Java Collection
.
It is the responsibility of the EJB container to maintain the referential integrity of these entity bean relationships.
For more information, see the following:
There is a notion of direction in CMR: a relationship may be either bidirectional or unidirectional. In a bidirectional relationship, each entity bean has a relationship field that refers to the other bean. Through the relationship field (see "Relationship Fields"), an entity bean's code can access its related object. In a unidirectional relationship, only one entity bean has a relationship field that refers to the other.
EJB QL queries (see "Understanding EJB QL") have an ability to navigate across relationships. The direction of a relationship determines whether or not a query can navigate from one bean to another.
A relationship field identifies a related bean. A relationship field behaves similar to a foreign key in a database table.
Like persistent fields (see "Container-Managed Persistent Fields"), relationship fields are virtual and are defined in the enterprise bean class with access methods. But to the contrary to persistent fields, relationship field do not represent the bean's state.
For more information about relationship fields, see "Configuring Container-Managed Relationship Fields".
There are a number of so-called callback methods that you must implement to enable the life cycle of your entity bean with container-managed persistence. Some of these methods are defined in the javax.ejb.EntityBean
interface, whereas the implementation of others (ejbCreate
and ejbPostCreate
) is mandated by the EJB 2.0 specification.
The container invokes the callback methods at the designated times; you may or may not add logic to these methods.
The following table provides each method's details, as well as lists the implementation requirements for the callback methods of the entity bean class:
You query for an instance of an entity bean using entity bean finder (see "Understanding Finder Methods") or select (see "Understanding Select Methods") methods.
You express your selection criteria using an appropriate query syntax (see "Understanding Query Syntax").
This section describes the following:
EJB Query Language (EJB QL) is a specification language used to define semantics of finder and select methods in a portable and optimizable format. The Orion persistence manager can perform an automatic compilation of EJB QL. Your responsibility is to define EJB QL queries in the deployment descriptor of the entity bean.
Using EJB QL offers the following advantages:
You do not need to know the database structure (such as tables and fields).
You can construct queries using the attributes of the entity beans instead of using database tables and fields.
You can use relationships in a query to provide navigation from attribute to attribute.
EJB QL queries are portable because they are database-independent.
You can specify the reference class in the SELECT
clause.
The disadvantage of EJB QL queries is that it is difficult to use when you construct complex queries.
EJB QL has the following restrictions:
Comments are not allowed.
Date and time values are in milliseconds and use a Java long
. A date or time literal should be an integer literal. To generate a millisecond value, you may use the java.util.Calendar
class.
In EJB 2.0 container-managed persistence does not support inheritance. For this reason, two entity beans of different types cannot be compared.
You can express an entity bean query using EJB QL (see "Understanding EJB QL") or SQL native to your underlying relational database.
EJB QL is preferred for it is portable and optimizable.
An EJB QL query has three clauses: SELECT
, FROM
, and WHERE
. The SELECT
and FROM
clauses are required, but the WHERE
clause is optional. The following is the high-level syntax of an EJB QL query:
EJB QL ::= select_clause from_clause [where_clause]
The SELECT
clause defines the types of the objects or values returned by the query. A return type is either a local interface, a remote interface, or a persistent field.
The FROM
clause defines the scope of the query by declaring one or more identification variables, which may be referenced in the SELECT
and WHERE
clauses. An identification variable represents one of the following elements:
The abstract schema name of an entity bean.
A member of a collection that is the multiple side of a one-to-many relationship.
The WHERE
clause is a conditional expression that restricts the objects or values retrieved by the query. Although optional, most queries have a WHERE
clause.
For more information about EJB QL syntax, consult EJB 2.0 specification at http://java.sun.com/products/ejb/docs.html
.
The EJB QL query syntax is demonstrated by the following example: suppose, you declare the findByZipCode
method in your entity bean's home interface to obtain all the Employee
beans with a certain zip code:
public Collection findByZipCode(String zipCode) throws RemoteException, CreateException
That would be expressed by using the following EJB QL statement in the deployment descriptor:
FROM contactInfo WHERE contactInfo.zip = ?1
This EJB QL statement says "select all the Employee
beans that have a zip code equal to the zipCode
argument." The SELECT
clause, which indicates what to select, is not needed in the EJB QL statements for find methods. That is because the finder methods will always select the remote references of its own bean type.
Native SQL is appropriate for taking advantage of advanced query features of your underlying relational database that EJB QL does not support.
You can use EJB QL in finder (see "Understanding Finder Methods") and select (see "Understanding Select Methods") methods. To use native SQL, you must use straight JDBC calls.
An EJB finder is a query, as defined by the EJB 2.0 specification. An EJB finder retrieves (and returns) entity bean references, whereas a query returns Java objects.
Finders contain finder methods (ejbFind
) that define search criteria.
The findByPrimaryKey
finder method is always defined in both home interfaces (local and remote) to retrieve the entity reference for this bean using a primary key. You can define other finder methods in either or both the home interfaces to retrieve one or several entity bean references.
Note: Finder methods are exposed to the client. |
For information on how to define and implement finder methods, see "Implementing EJB QL Finder Methods".
Select methods (ejbSelect
) are used primarily to return values of container-managed persistent (see "Container-Managed Persistent Fields") or relationship (see "Relationship Fields") fields. All values are returned in their own object type; any primitive types are wrapped in objects that have similar functions (for example, a primitive int
type is wrapped in an Integer
object). An ejbSelect
method is a query method intended for internal use within an entity bean instance. Specified in the abstract bean itself, the ejbSelect
method is not directly exposed to the client in the home or component interface. Defined as abstract, each bean can include zero or more such methods.
Select methods have the following characteristics:
The method name must have ejbSelect
as its prefix.
It must be declared as public
.
It must be declared as abstract
.
The throws
clause must specify the javax.ejb.FinderException
, although it may also specify application-specific exceptions as well.
Under EJB 2.0, the result-type-mapping
tag in the ejb-jar.xml
file determines the return type for ejbSelect
methods. Set the flag to Remote
to return EJBObject
; set it to Local
to return EJBLocalObject
.
For more information about select methods, see "Implementing EJB QL Select Methods".
Entity beans concurrency and database isolation levels let you avoid the resource contention and prevent the users from overwriting each others changes to database while allowing concurrent execution.
This section discusses the following topics:
Entity Bean Database Isolation Levels and Resource Contention
Combining Entity Bean Database Isolation Level and Concurrency Mode
The java.sql.Connection
object represents a connection to a specific database. The Connection
provides four database isolation levels to define protection against resource contention: when two or more users try to update the same resource, a lost update can occur. That is, one user can overwrite the other user's data without realizing it.
Oracle supports the following isolation levels:
transaction_read_committed
: Dirty reads are prevented; nonrepeatable reads and phantom reads can occur. This level only prohibits a transaction from reading a row with uncommitted changes in it.
transaction_serializable
: Dirty reads, nonrepeatable reads and phantom reads are prevented. This level includes the prohibitions in transaction_repeatable_read
and further prohibits the occurrence of the following hypothetical situation: one transaction reads all rows that satisfy a WHERE
condition; a second transaction inserts a row that satisfies that WHERE
condition; the first transaction rereads for the same condition, retrieving the additional "phantom" row in the second read.
For more information about database isolation levels, see "Configuring Database Isolation Levels".
OC4J also provides concurrency modes for handling resource contention and parallel execution within entity beans with container-managed persistence. The concurrency modes determine when to block to manage resource contention, or when to execute in parallel.
The following is the list of the available concurrency modes:
pessimistic: Manages resource contention and does not permit parallel execution. Only one user can execute the entity bean at a given time.
optimistic: Does not monitor resource contention. Thus, the database isolation levels manage the concurrency. Multiple users can execute the entity bean in parallel.
read-only: The container does not permit any updates to the bean's state. Multiple users can execute the entity bean in parallel.
For more information about concurrency modes, see "Configuring Concurrency Modes".
You can specify both entity bean concurrency modes and database isolation levels, if the combination affects the outcome of your resource contention. See "Combining Entity Bean Database Isolation Level and Concurrency Mode" for more information.
The setting of the database isolation level has no bearing on the pessimistic
and read-only
concurrency modes. The isolation levels only matter if an external source is modifying the database.
If you choose optimistic
concurrency mode with committed
database isolation level, you may lose an update. If you choose optimistic
concurrency mode with serializable
isolation level, you will never lose an update resulting in the constant consistency of your data. However, you can receive an ORA-8177
exception as a resource contention error.
An entity bean with the pessimistic
concurrency mode does not permit the execution by multiple clients (either on the same or on different instances of the same primary key). Only one client at a time can execute the instance.
An entity bean with the optimistic
concurrency mode allows multiple instances of the bean to execute in parallel. This might result in lost updates (and conflicts), because two different transactions may update the same row simultaneously.
Setting the transaction isolation level to serializable
enables the detection of conflicts when they occur. Currently, if an update from one of the transactions raises a SQLException
, that transaction is rolled back.
Optionally, you may set the tx-retries
attribute of the <entity-deployment>
element to a value greater than 1, which would result in the retry of the transaction. See Table A-1, "Attributes of the <entity-deployment> Element" for more information about the <entity-deployment>
element and its attributes.
All concurrency modes behave in a similar manner whether they are used within an independent or a clustered environment. This is because the concurrency modes are locked at the database level. Thus, even if a pessimistic bean instance is clustered across nodes, when one instance tries to execute the database locks out all other instances.
For more information, see the following:
"Clustering Overview" in the Oracle Containers for J2EE Configuration and Administration Guide
"Application Clustering in OC4J" in the Oracle Containers for J2EE Configuration and Administration Guide
"Oracle Application Server Cluster (OC4J) in Active-Active Topologies" in the Oracle Application Server High Availability Guide
You should consider using an entity bean with container-managed persistence under the following conditions:
The bean represents a business entity, not a procedure.
The bean's state is persistent: if the bean instance terminates or if the J2EE server shuts down, the bean's state still exists in a database.
The EJB container that you use delegates the persisting services to the Orion persistent manager.
Note: Oracle recommends migrating your application to the TopLink persistence manager using the Oracle migration tool. See "Migrating to the TopLink Persistence Manager" for more information. |