Java Reference
In-Depth Information
A stateless session bean class is annotated with the
@Stateless
annotation. In the
session bean class, an entity bean is created with the
create()
method. For example,
the
create()
method corresponding to the identifier property
catalogId
is
as follows:
public void create(String catalogId)
{ CatalogBean catalogBean = new CatalogBean(catalogId);
em.persist(catalogBean);
}
The
create()
method is a custom method as opposed to the
create()
method
of the EJB 2.0 specification; the method naming in the session bean façade may be
modified. The
persist()
method of the
EntityManager
class saves a new entity in
the database. The
remove()
method of the
EntityManager
class is used to remove
an entity:
public void remove(CatalogBean catalogBean) {
em.remove(catalogBean);
}
The
find()
method of the
EntityManager
class is used to find an entity bean.
In the session EJB, add finder methods for the named queries defined in the EJB
bean class. The
createNamedQuery()
method is used to obtain a query object for a
named query. For example, the finder method corresponding to the named query
FindByCatalogId
, which is defined in the entity class, is as follows:
public CatalogBean findByCatalogId(java.lang.String param1)
{Query query=em.createNamedQuery("FindByCatalogId");
query.setParameter(0, param1);
return (CatalogBean)(query.getSingleResult());
}
In the
findByCatalogId()
method, a
javax.persistence.Query
object is obtained
from the named query
FindByCatalogId
. The parameter values are set on the query
object. An entity EJB bean instance is obtained with the
getSingleResult()
method
of the query object. The named query
FindByCatalogId
returns a single entity of
the entity EJB bean. A named query may also return a collection of entities. For
example, the named query
FindByJournal
returns a collection. The finder method
corresponding to the
FindByJournal
named query is as follows.
public java.util.List<CatalogBean> findByJournal(java.lang.String
param1)
{ Query query= em.createNamedQuery("FindByJournal");
query.setParameter(0, param1);
Search WWH ::
Custom Search