#

Hibernate and Spring DAO Templates

Häufig genutzt, einmal notiert: Interface und abstrakte Implementierung von DAOs zur Benutzung mit Spring und Hibernate.

package project.dao;
 
import java.io.Serializable;
import java.util.List;
 
/**
 * D = domain object<br/>
 * K = Primary key of domain object, eg. Long<br/>
 * <p/>
 * @author M. Serhat Cinar
 *
 */
public interface Dao<D, K extends Serializable> {
	public D getById(K id);
	public void save(D d);
	public void delete(D d);
	public List<D> getAll(int offset, int amount);
	public List<D> getAll(int offset, int amount, String orderBy, boolean asc);
 
	/**
	 * Count of all available objects
	 * 
	 * @return Anzahl
	 */
	public long getTotalCount();
}
package project.dao.hibernate;
 
import java.io.Serializable;
import java.util.List;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
 
import project.dao.Dao;
 
/**
 * 
 * @author M. Serhat Cinar
 */
public abstract class AbstractDaoImpl<D, K extends Serializable> implements Dao<D, K> {
	private Log LOG = LogFactory.getLog(getClass());
	private SessionFactory sessionFactory;
 
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
 
	protected Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
 
	public void delete(D d) {
		getCurrentSession().delete(d);
	}
 
	@SuppressWarnings("unchecked")
	public List<D> getAll(int offset, int amount) {
		if (LOG.isDebugEnabled()){
			LOG.debug("getAll("+offset+","+amount+")");
		}
		List<D> list = getCurrentSession()
			.createQuery("FROM "+getDomain().getSimpleName())
			.setMaxResults(amount)
			.setFirstResult(offset)
			//.setFetchSize(amount)
			.list();
		if (LOG.isDebugEnabled()){
			LOG.debug("found "+list.size()+" datasets");
		}
		return list; 
	}
 
	@SuppressWarnings("unchecked")
	public List<D> getAll(int offset, int amount, String orderBy, boolean asc) {
		if (LOG.isDebugEnabled()){
			LOG.debug("getAll("+offset+","+amount+","+orderBy+","+
				(asc?"asc":"desc")+")");
		}
		List<D> list = getCurrentSession()
			.createQuery("FROM "+getDomain().getSimpleName()+
				" d ORDER BY d."+orderBy+" "+(asc?"ASC":"DESC"))
			.setMaxResults(amount)
			.setFirstResult(offset)
			//.setFetchSize(amount)
			.list();
		if (LOG.isDebugEnabled()){
			LOG.debug("found "+list.size()+" datasets");
		}
		return list; 
	}
 
	@SuppressWarnings("unchecked")
	public D getById(K id) {
		if (id==null){
			return null;
		}
		return (D) getCurrentSession().get(getDomain(), id);
	}
 
	/**
	 * Returns the domain class of this DAO. That's the class which is processed by this DAO.
	 * 
	 * @return domainclass of this DAO
	 */
	public abstract Class getDomain();
 
	public long getTotalCount() {
		Object result = getCurrentSession()
			.createQuery("SELECT COUNT(d.id) FROM "+
				getDomain().getSimpleName()+" d")
			.setMaxResults(1)
			.uniqueResult();
		if (result==null) return 0L;
		if (result instanceof Integer){
			return ((Integer) result).longValue(); 
		}
		return ((Long) result).longValue();
	}
 
	public void save(D d) {
		getCurrentSession().saveOrUpdate(d);
	}
}
Tags:, ,

3 Responses to “Hibernate and Spring DAO Templates” »»

  1. Comment by Jonata | 14:58 03.03.09|X

    And about applicationContext.xml?

  2. Comment by Paa | 15:29 15.02.10|X

    This looks really good.
    My question is, how do we extend AbstractDaoImpl with a specific domain object, say ‚Customer‘ and it’s configuration in the context file?

  3. Comment by Secco | 13:57 12.03.10|X

    If your customer Object has a Long primarykey it would look like this:

    public interface CustomerDao extends Dao<Customer, Long>{
      // special methods for customer dao
    }
    public class CustomerDaoImpl extends AbstarctDaoImpl<Customer, Long> implements CustomerDao{
      // implementation of special methods
    }

Leave a Reply »»

Note: All comments are manually approved to avoid spam. So if your comment doesn't appear immediately, that's ok. Have patience, it can take some days until I have the time to approve my comments.