DAO Layer & Service Manager Layer

All DAO classes will extend the GenericDao.java, which includes some common database actions, such as saveOrUpdate() and findByID(). Besides, it is also using to auto-wired the sessionFactory:

package com.itblogs.dao;

import java.util.List;

import java.io.Serializable;

import java.lang.reflect.ParameterizedType;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.criterion.Order;

import org.hibernate.Criteria;

import org.springframework.beans.factory.annotation.Autowired;


 * @author      Kelvin Hui

 * @see              it-blogs.com

 * @since            01-Jan-2016


public abstract class GenericDao<T> {


    private SessionFactory sessionFactory;

    private final Class<T> clazz;


    public GenericDao(){

       ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();

       this.clazz = (Class<T>) genericSuperclass.getActualTypeArguments()[0];


    public Session getSession(){

        return sessionFactory.getCurrentSession();


    protected Criteria createEntityCriteria(){

        return getSession().createCriteria(clazz);


    public T findByID(Serializable id) {

       return (T) getSession().get(clazz, id);


    public List<T> listAll(String orderBy, Boolean isAse) {

              Criteria criteria = createEntityCriteria();


              if( (orderBy!=null) && (isAse!=null) )

                     if(isAse) { criteria.addOrder(Order.asc(orderBy)); } else { criteria.addOrder(Order.desc(orderBy)); }

              return (List<T>) criteria.list();


    public long countAll() {

       return (Long) getSession().createQuery(“SELECT COUNT(*) FROM ” + clazz.getName()).uniqueResult();


    public void saveOrUpdate(T t) {



       public void deleteRecord(T t) {



       public void deleteRecordByID(Serializable id) {

              T t = (T) getSession().get(clazz, id);




    public boolean containsRecord(Serializable id) {

        return (T) getSession().get(clazz.getName(), id) != null;




Please download here to get the DAO and Service Manager classes. Besides the above generic database common functions, you can also define some specified database functions for each of the table.


With layering structure, the controller will call Service Manager, and Service Manager calls DAO.


It is suggested to define the service manager classes as @Transactional. You can also include some business logic insides the service manager, instead of writing in controller and DAO. Try to keep DAO as simple as you can, just have the database functions.

Please rate this