Migrating EJB 2.1 Entity and Session Beans to EJB 3.0
The nuts and bolts
Posted in Developer, 25th April 2006 06:02 GMT
Free Download - Security Web 2.0
Table 2. EntityManager Class
| EntityManager Method | Description |
|---|---|
| persist | Creates an entity bean instance. |
| createNamedQuery | Creates a named query. |
| find | Finds an entity bean instance. |
| createQuery | Creates an EJBQL query. |
| remove | Removes an entity bean instance. |
In a session bean client class for EJB 3.0 entity bean, the EntityManager reference is obtained with the @Resource annotation:
@Resource private EntityManager em;
An entity bean instance is created with the persist() method of the EntityManager class:
CatalogBean catalogBean=new CatalogBean(catalogId); em.persist(catalogBean);
An entity bean instance is obtained with the find() method:
CatalogBean catalogBean=(CatalogBean)em.find("CatalogBean", catalogId);
A finder method may be defined corresponding to the named query findByJournal in the entity bean POJO class. In the finder method a Query object is obtained with the createNamedQuery method:
Query query=em.createNamedQuery("findByJournal");
Set the Query object parameters with the setParameter method:
query.setParameter(0, journal);
Obtain a Collection of the CatalogBean with the getResultList() method. If a Query object returns a single result, the getSingleResult() is used:
java.util.Collection catalogBeanCollection=(CatalogBean)query.getResultList();
An entity bean instance is removed with the remove() method of the EntityManager class:
CatalogBean catalogBean; em.remove(catalogBean);
The client class for the EJB 3.0 entity bean is listed in Listing 9.
Listing 9. CatalogClient. EJB 3.0 Client Class
import javax.ejb.Stateless;
import javax.ejb.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
@Stateless
@Local
public class CatalogClient implements CatalogLocal {
@Resource
private EntityManager em;
public void create(String catalogId) {
CatalogBean catalogBean=new CatalogBean(catalogId);
em.persist(catalogBean);
}
public CatalogBean findByPrimaryKey(String catalogId) {
return (CatalogBean)em.find("CatalogBean", catalogId);
}
public java.util.Collection findByJournal(String journal) {
Query query=em.createNamedQuery("findByJournal");
query.setParameter(0, journal);
return (CatalogBean)query.getResultList();
}
public void remove(CatalogBean catalogBean) {
em.remove(catalogBean);
}
}
Next page: Summary

Implementing Energy Efficient Data Centers [WP114]
An Improved Architecture for High-Efficiency, High-Density Data Centers [WP126]
The Register Guide to Extended Validation
Software Configuration Management
The Perfect (Virtual) Marriage
How Microsoft blew its own RIA invention
Java and Linux - an open marriage in search of success
Rock-solid Fedora 10 brings salvation to Ubuntu weary
Hidden recipes for OS X charts and graphs