«

»

Nov
24

Generic DAO with Hibernate and Spring

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>
VN:F [1.9.14_1148]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.14_1148]
Rating: 0 (from 0 votes)

About the author

Faisal Basra

Faisal Basra is an independent consultant, software developer, writer, blogger, speaker, architect and technology leader in Lahore, Pakistan. He has been a professional software developer since 2008, has been writing code since 2006.Having hands on experience of popular Java EE frameworks & technologies like JSF, Spring, Hibernate, Enverse, JPA, Richfaces, Primefaces, JSP/Servlet.Tools & Servers: jUnit, Log4j, Maven, Eclipse, MyEclipse, NetBeans, Tomcat, Jboss, WebLogicMobile Development: Google Android

Permanent link to this article: http://www.javaplex.com/blog/generic-dao-with-hibernate-and-spring/

2 comments

  1. Mnomansadiq says:

    Spring already support the generic template, HibernateTemplate or JDBCTemplate better to use that instead to create your own.

    VA:F [1.9.14_1148]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.14_1148]
    Rating: 0 (from 0 votes)
  2. Salman Khursheed Khaleeqi Naqs (http://www NULL.facebook NULL.com/salman NULL.khaleequi NULL.naqshbandi) says:

    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.

    VA:F [1.9.14_1148]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.14_1148]
    Rating: -1 (from 1 vote)

    Leave a Reply

    Your email address will not be published.

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>