Java Reference
In-Depth Information
Next, create a test() method, which we shall invoke from a test client. In the
test() method we shall create and persist entity instances, query an entity instance,
and delete an entity instance, all using an EntityManager object, which we had
injected earlier in the session bean class. Injecting an EntityManager implies that an
instance of EntityManager is made available to the session bean. Create an instance
of the Entity bean class:
Catalog catalog = new Catalog(new Integer(1), "Oracle Magazine",
"Oracle Publishing", "September-October 2009",
"Put Your Arrays in a Bind","Mark Williams");
Persist the entity instance to the database using the persist() method:
em.persist(catalog);
Similarly, persist two more entity instances. Next, create a query using the
createQuery() method of the EntityManager object. The query string may
be specified as a EJB-QL query. Unlike HQL, the SELECT clause is not optional
in EJB-QL. Execute the query and return the query result as a List using the
getResultList() method. As an example, select the catalog entry corresponding
to author David Baum . The FROM clause of a query is directed towards the mapped
entity bean class, not the underlying database.
List catalogEntry =em.createQuery("SELECT c from Catalog c where
c.author=:name").setParameter("name","David Baum").
getResultList();
Iterate over the result list to output the properties of the entity instance:
for (Iterator iter = catalogEntry.iterator(); iter.hasNext(); ) {
Catalog element = (Catalog)iter.next();
retValue =retValue + "<br/>" + element.getJournal() +
"<br/>" + element.getPublisher() +"<br/>" +
element.getDate() + "<br/>" + element.getTitle() +
"<br/>" + element.getAuthor() +"<br/>";
}
The variable retValue is a String that is returned by the test() method. Similarly,
create and run a EJB-QL query to return all titles in the Catalog database:
List allTitles =em.createQuery("SELECT c from Catalog c").
getResultList();
An entity instance may be removed using the remove() method:
em.remove(catalog2);
 
Search WWH ::




Custom Search