一、前言
基于Hibernate实现通用GenericDao接口的GenericDaoHibernate实现类,详情参见代码示例说明部分。
二、代码示例
1. GenericDao通用dao接口
import java.util.List;@b@@b@public abstract interface GenericDao<T> {@b@ @b@ public abstract T get(Long paramLong);@b@@b@ public abstract List<T> getAll();@b@@b@ public abstract void save(T paramT);@b@@b@ public abstract void save(List<T> paramList);@b@@b@ public abstract void delete(T paramT);@b@@b@ public abstract void delete(List<T> paramList);@b@@b@ public abstract List<T> queryByExample(T paramT);@b@@b@ public abstract void saveOrUpdate(T paramT);@b@ @b@}
2. GenericDaoHibernate通用接口实现类
import java.util.List;@b@import org.hibernate.Criteria;@b@import org.hibernate.Session;@b@import org.hibernate.SessionFactory;@b@import org.hibernate.criterion.Example;@b@import org.springframework.beans.factory.annotation.Autowired;@b@@b@import dao.GenericDao;@b@@b@public class GenericDaoHibernate<T> implements GenericDao<T> {@b@ @b@ private Class<T> type;@b@ private SessionFactory sessionFactory;@b@@b@ public GenericDaoHibernate(Class<T> type) {@b@ this.type = type;@b@ }@b@@b@ public T get(Long id) {@b@ return ((T) getCurrentSession().get(this.type, id));@b@ }@b@@b@ public List<T> getAll() {@b@ return getCurrentSession().createCriteria(this.type).list();@b@ }@b@@b@ public void save(T entity) {@b@ getCurrentSession().save(entity);@b@ getCurrentSession().flush();@b@ }@b@@b@ public void save(List<T> entities) {@b@ int count = 0;@b@ label57: for (T object : entities) {@b@ save(object);@b@ if (++count % 100 != 0)@b@ break label57;@b@ getCurrentSession().flush();@b@ getCurrentSession().clear();@b@ }@b@ }@b@@b@ public void delete(T entity) {@b@ getCurrentSession().delete(entity);@b@ }@b@@b@ public void delete(List<T> entities) {@b@ for (T entity : entities)@b@ delete(entity);@b@ }@b@@b@ public void saveOrUpdate(T entity) {@b@ getCurrentSession().saveOrUpdate(entity);@b@ }@b@@b@ public List<T> queryByExample(T example) {@b@ Criteria crit = getCurrentSession().createCriteria(this.type);@b@@b@ crit.add(Example.create(example));@b@ return crit.list();@b@ }@b@@b@ @Autowired@b@ public void setupSessionFactory(SessionFactory sessionFactory) {@b@ this.sessionFactory = sessionFactory;@b@ }@b@@b@ protected Session getCurrentSession() {@b@ return this.sessionFactory.getCurrentSession();@b@ }@b@ @b@}