If you are using Hibernate with Spring, then you will be dealing with huge set of DAOs. In such case best way to minimize the DAO work with Generic DAO patter, which encapsulate CRUD + basic finder method and then write only very required methods.
I’m inspired by the IBM Generic DAO pattern and rewrite it by using Hibernate & Spring, by most cases we use these both technologies in our Java EE application.
When you can extend from this class and you will have all the method required for basic operation which will save a lot of time with repetitive code. You are welcome to comment & suggest for any improvement.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateTemplate;
@SuppressWarnings("unchecked")
public class StatefullDAOSupport{
@Autowired
private HibernateTemplate hibernateTemplate;
protected Logger logger = Logger.getLogger(StatefullDAOSupport.class.getName());
public StatefullDAOSupport() {
super();
}
@SuppressWarnings("unchecked")
public <T> List<T> findAll(Class<T> entityClass) throws DataAccessException {
getHibernateTemplate().setCacheQueries(true);
List<T> results = getHibernateTemplate().loadAll(entityClass);
Set<T> set = new HashSet<T>(results);
results = new ArrayList<T>(set);
return results;
}
@SuppressWarnings("unchecked")
public <T> T findById(Class<T> entityClass, Long id) throws DataAccessException {
getHibernateTemplate().setCacheQueries(true);
T object = (T) getHibernateTemplate().get(entityClass, id);
if(object == null){
logger.warn("entity with id '" + id + "' not found.");
throw new ObjectRetrievalFailureException(entityClass, id);
}
else {
return object;
}
}
public <T> void saveOrUpdate(T entity) throws DataAccessException {
getHibernateTemplate().saveOrUpdate(entity);
}
public <T> T merge(T entity) throws DataAccessException {
return (T) getHibernateTemplate().merge(entity);
}
public <T> void remove(T entity) throws DataAccessException {
getHibernateTemplate().delete(entity);
}
public <T> void removeAll(Class<T> entityClass) throws DataAccessException {
getHibernateTemplate().deleteAll(this.findAll(entityClass));
}
public <T> List<T> findByNamedQueryAndNamedParam(Class<T> entityClass,
String queryName, String[] paramNames, Object[] values) throws DataAccessException {
List<T> results = (List<T>) getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, paramNames, values);
return results;
}
public <T> List<T> findByNamedQueryAndNamedParam(Class<T> entityClass,
String queryName, Map<String, ?> params) throws DataAccessException {
String[] paramNames = new String[params.size()];
Object[] values = new Object[params.size()];
List<String> keys = new ArrayList<String>(params.keySet());
for(int i=0; i<keys.size(); i++){
String key = keys.get(i);
paramNames[i] = key;
values[i] = params.get(key);
}
return this.findByNamedQueryAndNamedParam(entityClass, queryName, paramNames, values);
}
public <T> List<T> findByNamedParam(Class<T> entityClass, String query,
String[] paramNames, Object[] values) throws DataAccessException {
List<T> results = (List<T>) getHibernateTemplate().findByNamedParam(query, paramNames, values);
return results;
}
public <T> List<T> findByNamedParam(Class<T> entityClass, String query,
Map<String, ?> params) throws DataAccessException {
String[] paramNames = new String[params.size()];
Object[] values = new Object[params.size()];
List<String> keys = new ArrayList<String>(params.keySet());
for(int i=0; i<keys.size(); i++){
String key = keys.get(i);
paramNames[i] = key;
values[i] = params.get(key);
}
List<T> results = (List<T>) getHibernateTemplate().findByNamedParam(query, paramNames, values);
return results;
}
}
How to declare HibernateTemplate so spring AOP container can autowrire
<bean name="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean>

2 comments
Mnomansadiq says:
November 25, 2011 at 3:13 pm (UTC 5)
Spring already support the generic template, HibernateTemplate or JDBCTemplate better to use that instead to create your own.
Salman Khursheed Khaleeqi Naqs (http://www NULL.facebook NULL.com/salman NULL.khaleequi NULL.naqshbandi) says:
November 26, 2011 at 4:22 pm (UTC 5)
That’s wonderful sharing… keep it up Faisal.
@Mnomansadiq
You can see underlying is still Spring’s HibernateTempalte, what is generic Generic DAO pattern is, you should not need to create each DAO for each Entity but still want to have control before going to spring.