Java Reference
In-Depth Information
When a concrete DAO subclass is instantiated, entityClass will contain
the specific model class. This is very handy to write the rest of the
BaseDaoImpl code in a generic fashion. For example, here's how we
implement the read methods:
Download email_23/src/stripesbook/dao/impl/stripersist/BaseDaoImpl.java
@SuppressWarnings("unchecked")
public List<T> read() {
return Stripersist.getEntityManager()
.createQuery("from " + entityClass.getName())
.getResultList();
}
public T read(ID id) {
return Stripersist.getEntityManager().find(entityClass, id);
}
There are a few things going on here. First, Stripersist.getEntityManager ( )
returns an implementation of the JPA's EntityManager interface that we
can use to work with the database. JPA requires you to create an Entity-
ManagerFactory (normally at application startup), use it to create an Enti-
tyManager , close ( ) the EntityManager when you're done with it, and close ( )
the EntityManagerFactory when the application shuts down. Stripersist
takes care of all that housekeeping for you!
Next, the entity's class name is dynamically added to the query passed
to createQuery ( ) in order to retrieve the list of objects for that entity.
Finally, EntityManager provides a method to retrieve an entity object by
its ID, which is used in the read(ID) method.
Note that we called Stripersist.getEntityManager ( ) with no parameters. This
works because we defined only one persistence unit in the persistence.xml
file:
<persistence-unit name="stripes_webmail">
...
</persistence-unit>
With more than one persistence unit, we would pass the name of the
persistence unit as a parameter, as in Stripersist.getEntityManager("stripes_
webmail") .
At this point, we're only reading objects. We also need to create, update,
and delete objects. Unlike reading, these operations involve changing
the database. You are no doubt familiar with database transactions;
in a nutshell, a transaction is a way to group one or more operations
for which it is important that either all or none of the operations go
through to the database. The typical example is a bank transaction that
 
 
Search WWH ::




Custom Search