Java Reference
In-Depth Information
Using Stripersist and JPA in the DAOs
We've gotten pretty far already. We now need to write the code that
creates, updates, and deletes model objects, as well as reads them by
something else than their @Id . The DAOs are the perfect place for this
code. Remember our generic DAO interface:
Download email_23/src/stripesbook/dao/Dao.java
package stripesbook.dao;
public interface Dao<T,ID extends Serializable> {
public List<T> read();
public T read(ID id);
public void save(T t);
public void delete(T t);
public void commit();
}
The mock DAOs that we were previously using just assumed an ID
property of type Integer . Now that we're using the @Id annotation to
indicate the ID property, we have to be a little more flexible. That's
why the Dao interface is generic not only for the model type T but also
the type of the ID property, ID . JPA requires @Id property types to be
Serializable , which is why the Dao imposes this restriction.
The DAO interface also includes a commit ( ) method so that transactions
can be committed. More about this very shortly. Because the methods
in the Dao interface are common to all model objects, it makes sense
to write an abstract base class that provides a generic implementation
for any type. Each specific DAO extends this base class and needs to
provide only what is specific to the corresponding model class.
Let's create the BaseDaoImpl class and use a little bit of Java generics
magic to detect the model class that the DAO is dealing with:
Download email_23/src/stripesbook/dao/impl/stripersist/BaseDaoImpl.java
package stripesbook.dao.impl.stripersist;
public abstract class BaseDaoImpl<T,ID extends Serializable>
implements Dao<T,ID>
{
private Class<T> entityClass;
@SuppressWarnings("unchecked")
public BaseDaoImpl() {
entityClass = (Class<T>)
((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
}
/ * methods... * /
}
 
 
Search WWH ::




Custom Search