Skip to main content

Hibernate Generic DAO.

When you use Hibernate and DAO pattern it is a good idea to use a Generic Base Dao. The fallowing code snippet contains GenericDAO that is a base class for all my DAO classes. This GenericDAO uses HibernateDaoSupport from Spring for its implementation if you want you can use JpaDaoSupport or JdbcDaoSupport in your projects.

My Generic DAO interface looks like this :

package org.joke.myproject.dao.base;

import java.io.Serializable;

import java.util.List;

/**

* @author Naiden Gochev

* @param <E>

* @param <PK>

*/

public interface GenericDao<E,PK  extends Serializable> {

    PK save(E newInstance);

    void update(E transientObject);

    void saveOrUpdate(E transientObject);

    void delete(E persistentObject);

    E findById(PK id);

    List<E> findAll();

    List<E> findAllByProperty(String propertyName,Object value);

}

All method names are very common so I don't think they need some explanation.

The implementation of this GenericDAO :

package org.joke.myproject.dao.base;

 

import java.io.Serializable;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;

import org.hibernate.criterion.Restrictions;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**

* @author JOKe

* @param <E>

* @param <PK>

*/

public abstract class GenericDaoImpl<E, PK extends Serializable> extends

            HibernateDaoSupport implements GenericDao<E, PK> {

      @SuppressWarnings("unchecked")

      public PK save(E newInstance) {

            return (PK) getHibernateTemplate().save(newInstance);

      }

      @SuppressWarnings("unchecked")

      public E findById(PK id) {

            return (E) getHibernateTemplate().get(getEntityClass(), id);

      }

      @SuppressWarnings("unchecked")

      public List<E> findAll() {

            return getHibernateTemplate().findByCriteria(createDetachedCriteria());

      }

      @SuppressWarnings("unchecked")

      public List<E> findAllByProperty(String propertyName, Object value) {

            DetachedCriteria criteria = createDetachedCriteria();

            criteria.add(Restrictions.eq(propertyName, value));

            return getHibernateTemplate().findByCriteria(criteria);

      }

      public List<E> findByExample(E object) {

            List<E> resultList = getHibernateTemplate().findByExample(object, 0, 1);

            return resultList;

      }

      public List<E> findByExample(E object, int firstResult, int maxResults) {

            List<E> resultList = getHibernateTemplate().findByExample(object,

                        firstResult, maxResults);

            return resultList;

      }

      public void update(E transientObject) {

            getHibernateTemplate().update(transientObject);

      }

      public void saveOrUpdate(E transientObject) {

            getHibernateTemplate().saveOrUpdate(transientObject);

      }

      public void delete(E persistentObject) {

            getHibernateTemplate().delete(persistentObject);

      }

      protected abstract Class<E> getEntityClass();

      protected DetachedCriteria createDetachedCriteria() {

            return DetachedCriteria.forClass(getEntityClass());

      }

}

The GenericDaoImpl is abstract because the actual DAOs will extend it and will override only one method :  protected abstract Class<E> getEntityClass(); This method is used for creating of the DetachedCriteria object in the createDetachedCriteria() method.

Every DAO class that implements GenericDaoImpl will look like this :

package org.joke.myproject.dao;

 

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;

import org.hibernate.criterion.Restrictions;

import org.joke.myproject.dao.base.GenericDaoImpl;

import org.joke.myproject.entity.Message;

 

public class MessagesDAO extends GenericDaoImpl<Message, Integer> {

      @Override

      protected Class<Message> getEntityClass() {

            return Message.class;

      }

      public List<Message> findNotDeletedTextMessages() {

            DetachedCriteria criteria = createDetachedCriteria();

            criteria.add(Restrictions.eq("deleted", false));

            criteria.add(Restrictions.or(Restrictions.eq("custom", false), Restrictions.isNull("custom")));

            List<Message> textMessages = getHibernateTemplate().findByCriteria(criteria);

            return textMessages;

      }

}

The method here called findNotDeletedTextMessages() is optional it is just another DAO method added in the implementation. If you use Spring you can just add the annotation @Component as class annotation and you have DAO ready for use.

That's all have fun.

Edit : Check out my next article called  JSF, Spring, Hibernate – lets make development easy. It will use this GenericDAO to make architecture of an application.

Comments

Nice post.

Though as I mentioned here I would prefer to throw HibernateTemplate away and use plain hibernate 3 style instead.
jNayden said…
:) maybe it is better but the most common way is to use template(s).
Unknown said…
Hey, this is pretty similar to the way my apps are set up... one slight difference is that rather than having an abstract method to get the persistent class, I use some good old reflection.

In the base dao constructor, I have the following:

ParameterizedType pType = (ParameterizedType) getClass().getGenericSuperclass();
this.persistentClass = (Class<T>) pType.getActualTypeArguments()[0];


So if the implementation extends GenericDaoImpl<Message, Integer>, this.persistentClass will be a Message.class.

I think I originally got this from Christian Bauer's blog.

So long as you're on Sun's JVM 1.5+ the reflection's lightning fast, and as it only runs once per dao instance (probably during the apps bootstrap phase) there's really no reason not to do this (in my opinion).
jNayden said…
Hm yes you are right there is only one instance of this DAO so the reflection will not slow the application. Thanks man :) I will "update" my projects genericDao :D
Very good. I did one minor change, because we deal with multiple Hibernate session factories. In such a scenario they need to pass in into the constructor:

@SuppressWarnings("unchecked")
protected GenericDaoImpl(SessionFactory sf) {
setSessionFactory(sf);
}

And then each concrete implementation passes in the SessionFactory that it is actually bound to:

@Autowired
public ConcreteDao(@Qualifier(ApsConstants.LOCAL_HSF) SessionFactory sf) {
super(sf);
}
Tauren Mills said…
Nothing against your generic dao implementation, but I've been using this project recently and have been pleased.
http://code.google.com/p/hibernate-generic-dao/
Toi said…
Is it in appfuse a long time ago?
JavaTution said…
Very useful information. Keep on posting. www.javatutoronline.com
the classes User and AuctionDataProvider must be Serializable, then works fine.

tested on JBoss 4.2.1.
It is very very informative. I liked the way you have explained.Java Online Training

Popular posts from this blog

Use Client Certificate Authentication with Java and RestTemplate

As a follow up of the  http://gochev.blogspot.com/2019/04/convert-pfx-certificate-to-jks-p12-crt.html  we now have a keystore and a truststore (if anyone needs) and we will use this keystore to send client side authentication using Spring's RestTemplate . First copy your keystore.jks and truststore.jks in your classpath, no one wants absolute paths right ?:) Again a reminder  The difference between truststore and keystore if you are not aware is(quote from the   JSSE ref guide ) :   TrustManager: Determines whether the remote authentication credentials (and thus the connection) should be trusted. KeyManager: Determines which authentication credentials to send to the remote host. The magic happens in the creation of SSLContext. Keep in mind the Spring Boot have a nice RestTemplateBuilder but I will not gonna use it, because someone of you might have an older version or like me, might just use a plain old amazing Spring. If you just want to use the keystore: final Stri

Convert PFX certificate to JKS, P12, CRT

I recently had to use a PFX certificate for client authentication (maybe another post will be coming) and for that reason I had to convert it to a Java keystore (JKS).  We will create BOTH a truststore and a keystore, because based on your needs you might need one or the other.  The difference between truststore and keystore if you are not aware is(quote from the JSSE ref guide : TrustManager: Determines whether the remote authentication credentials (and thus the connection) should be trusted. KeyManager: Determines which authentication credentials to send to the remote host. Ok that's enough what you will need is openssl and Java 7+ ;) ! First let's generate a key from the pfx file, this key is later used for p12 keystore. openssl pkcs12 -in example.pfx -nocerts -out  example .key   Enter Import Password: MAC verified OK Enter PEM pass phrase: Verifying - Enter PEM pass phrase: As shown here you will be asked for the password of the pfx file, l

Use Multiple JVM versions on Mac OS and Linux

Linux Download multiple Java versions and put them into /opt/ If you already have some JDK from ubuntu repo or etc not a big deal, just fix the paths bellow Register them as alternatives sudo update-alternatives --install /usr/bin/java java /opt/java-8-oracle/bin/java 1081 sudo update-alternatives --install /usr/bin/java java /opt/sap-machine-jdk-11.0.3/bin/java 1080 Edit your ~/.bashrc file alias java11='sudo update-alternatives --set java /opt/sapmachine-jdk-11.0.3/bin/java;export JAVA_HOME=/opt/sapmachine-jdk-11.0.3/' alias java8='sudo update-alternatives --set java /opt/java-8-oracle/bin/java;export JAVA_HOME=/usr/lib/java-8-oracle/' SAVE and start a new bash terminal execute java8 to use java8 java11 to use java11 the latest version you have set stays as system wide, but the JAVA_HOME is not :( you can put java8 or java11 as a last line in the bashrc but since it is sudo it will always require password when start and is not gr