A Generic DAO for Hibernate and JPA
This is just a little tip, nothing earth-shattering. ;-) On a few projects I've seen a DAO written or generated for every entity. Most of these DAOs only contained the methods for CRUD operations (Create, Update, Delete) on that entity. That meant a lot of needless repetition. With generics, introduced in Java 5, we can build a type-safe generic DAO that does the job of those generated objects.
public class GenericDAO<E extends Object>{
private Class entityClass;
protected GenericDAO(Class entityClass) {
this.entityClass = entityClass;
}
public E get(Serializable id) {
return (E) getSesion().get(entityClass, id);
}
public void save(E entity) {
getSesion().save(entity);
}
public void update(E entity) {
getSesion().save(entity);
}
public void delete(E entity) {
getSesion().delete(entity);
}
protected Session getSesion() {
return null; //get Hibernate session from somewhere
}
protected Class getEntityClass() {
return entityClass;
}
public static <T extends Object> GenericDAO createGenericDAO(Class clazz) {
GenericDAO dao = new GenericDAO(clazz);
return dao;
}
}
Once it's set up, the DAO is easy to use in your code.
GenericDAO dao = GenericDAO.createGenericDAO(Dog.class);
Dog dog = dao.get(1);
Related articles
Related CZ Podcast episodes
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio
- #1 · Vývojová prostředí v Javě
The first CZ Podcast episode looks at Java development environments. · Czech audio