Java Reference
In-Depth Information
The
CatalogTestSessionEJBBean
class is annotated with the annotation
@Stateless
. The
mappedName
attribute specifies the global JNDI for the session
bean. We shall use the mapped name in the test client to lookup the session bean and
invoke method/s on it. The
@Remote
annotation indicates that the session bean is a
remote interface.
@Stateless(name = "CatalogTestSessionEJB", mappedName = "EJB3-
SessionEJB")
@Remote
public class CatalogTestSessionEJBBean implements
CatalogTestSessionEJB { }
In the session bean an
EntityManager
is injected using the
@PersistenceContext
annotation. The
unitName
is specified, but not required, as the
EntityManager
variable name is the same as the persistence unit name.
@PersistenceContext(unitName = "em")
private EntityManager em;
Add a method
test()
to the session bean and the remote interface. In the
test()
method, create a
Catalog
entity instance with the
new
operator:
Catalog catalog =new Catalog("Kimberly Floss", "Nov-Dec 2004", new
Integer(1),"Oracle Magazine", "Oracle Publishing","Database Resource
Manager");
Invoke the
persistEntity(Object)
method to persist the entity bean instance:
persistEntity(catalog);
The
persistEntity
method invokes the persist method of the
EntityManager
to
persist the entity bean:
em.persist(entity);
Similarly, persist two more entity bean instances. Next, create an instance of the
Query
object using the
createQuery
method to run a Java Persistence Query
Language statement. Bind an author name to the named parameter
:name
using
the
setParameter
method, and run the Java persistence query statement using the
getResultList
method, which returns a
List
:
List catalogEntry =
em.createQuery("SELECT c from Catalog c where
c.author=:name").setParameter("name","Jonas Jacobi").getResultList();
Iterate over the
List
, which is actually just one catalog entry, to output field values
for the
journal
,
publisher
,
edition
,
title
, and
author
fields:
for (Iterator iter = catalogEntry.iterator(); iter.hasNext(); )
Search WWH ::
Custom Search