Migrating Entity Beans
This section shows how to migrate an EJB 2.1 entity bean to the EJB 3.0 specification. An EJB 2.1 entity bean implements the EntityBean interface and consists of getter and setter CMP field methods, getter and setter CMR field methods, callback methods, and ejbCreate/ejbPostCreate
methods. The example entity bean, BookCatalogBean.java (see Listing 1
), consists of the CMP fields title
, and publisher
, and the CMR field editions
deployment descriptor for this EJB 2.1 entity bean (see Listing 2
), specifies the EJB classes and interfaces, CMP fields, EJB QL queries, and CMR relationships. The BookCatalogBean entity bean defines a finder method, findByTitle()
, and a CMR field, editions
In contrast, the EJB 3.0 entity bean class that corresponds to the EJB 2.1 bean class is a Plain Old Java Object (POJO), and it's far simpler (see Listing 3). The EJB 3.0 version of this bean class uses the metadata annotation @Entity. The finder methods, specified in the EJB 2.1 deployment descriptor ejb-jar.xml file with elements, are specified in the EJB 3.0 bean class with the @NamedQueries and @NamedQuery annotations. The CMR relationships, specified in the ejb-jar.xml file with elements, are specified in the EJB 3.0 bean class with metadata annotations. The primary key field is specified with the annotation @Id. Some of the EJB 3.0 metadata annotations are discussed in Table 1.
Table 1. EJB 3.0 Metadata Annotations: The table shows common EJB 3.0 metadata annotations, a brief description, and when appropriate, the elements affected by the annotation.
||Annotates an entity bean class.
||Annotates the entity bean table. If @Table is not specified, the table name is same as the EJB name.
||Annotates a primary key property or field.
||Annotates a non persistent property or field.
||Annotates a mapped column for a persistent entity bean property.
||name, primaryKey, nullable, length.Default column name is the property or field name.
||Annotates a group of named queries.
||Annotates a named query or a query associated with a finder method
||Annotates a one-to-many association.
||Annotates a one-to-one association.
||Annotates a many-to-many association.
||Annotates a many-to-one association.
You'll find the EJB 3.0 annotation type corresponding to the finder method findByTitle()
in the EJB 2.1 bean class, the EJB 3.0 version uses the @NamedQuery
annotation. Corresponding to the CMR relationship BookCatalog-Editions in the EJB 2.1 entity bean, the EJB 3.0 entity bean uses a @OneToMany
annotation. The @Id
annotation annotates the identifier property title
. The @Column
annotation specifies the database column that corresponds to the identifier property title
. If a persistent entity bean property is not annotated with @Column
annotation, the EJB server assumes the column name is same as the entity bean property name. Transient entity bean properties are annotated with the @Transient