Hibernate的通用dao

关键字: spring, hibernate, 通用dao

Hibernate+spring通用的dao.
首先定义一个SimpleDao接口,里面的方法如下:

Java代码
  1. /*  
  2.  *   
  3.  * @author zyong  
  4.  *  
  5.  * @date 2009-9-19 下 午11:02:34  
  6.  *  
  7.  * @action 一个简单公共的hibernate通用dao实现类  
  8.  */   
  9. package  com.wind.dao;  
  10.   
  11. import  java.io.Serializable;  
  12. import  java.util.Collection;  
  13. import  java.util.List;  
  14. import  java.util.Map;  
  15.   
  16. import  org.hibernate.Criteria;  
  17. import  org.hibernate.HibernateException;  
  18. import  org.hibernate.LockMode;  
  19. import  org.hibernate.criterion.DetachedCriteria;  
  20.   
  21. /**  
  22.  *   
  23.  * @author zyong  
  24.  *   
  25.  * @action 一 个通用的Hibernate的dao接口<br>  
  26.  *         数据访问层里面的每一个接口都应该继承这个接口<br>  
  27.  *         而不用重写里面的方法  
  28.  */   
  29. public   interface  SimpleDao<E  extends  Serializable, PK  extends  Serializable> {  
  30.   
  31.     /**  
  32.      *   
  33.      * 该枚举类型用于,getStackValue方法中的Stack枚举  
  34.      *   
  35.      */   
  36.     enum  Stack {  
  37.         MAX, MIN, AVG, SUM;  
  38.     }  
  39.   
  40.     /**  
  41.      *   
  42.      * @param id  
  43.      *            根据主键查询一个实体  
  44.      * @return 一个实体对象  
  45.      */   
  46.     E get(PK id);  
  47.   
  48.     /**  
  49.      *   
  50.      * @param id  
  51.      *            根据主键查询一个实体  
  52.      * @param lock  
  53.      *            加锁实体  
  54.      * @return 一个实体对象  
  55.      */   
  56.     E get(PK id, LockMode lock);  
  57.   
  58.     /**  
  59.      * 使 用数据库函数  
  60.      *   
  61.      * @param criteria  
  62.      *            一个DetacherCriteria对象  
  63.      * @param propertyName  
  64.      *            实体类属性名  
  65.      * @param stackName  
  66.      *            Stack枚举类型中的任意一个  
  67.      * @return 一行一列数据库  
  68.      */   
  69.     Object getStackValue(DetachedCriteria criteria, String propertyName,  
  70.             String stackName);  
  71.   
  72.     /**  
  73.      * 查 询数据库对应的记录数  
  74.      *   
  75.      * @param criteria  
  76.      *            一个DetachedCriteria对象  
  77.      * @return 记录数  
  78.      */   
  79.     Integer getRowCount(DetachedCriteria criteria);  
  80.   
  81.     /**  
  82.      *   
  83.      * @param id  
  84.      *            根据主键加裁一个实体对象  
  85.      * @return 一个实体对象  
  86.      */   
  87.     E load(PK id);  
  88.   
  89.     /**  
  90.      *   
  91.      * @param id  
  92.      *            根据主键加裁实体  
  93.      * @param lock  
  94.      *            加锁实体  
  95.      * @return 一个实体对象  
  96.      */   
  97.     E load(PK id, LockMode lock);  
  98.   
  99.     /**  
  100.      *   
  101.      * @return 加 裁所有对象  
  102.      */  
  103.     List<E> loadAll();  
  104.   
  105.     /**  
  106.      *   
  107.      * @param entity  
  108.      *            保存一个实体  
  109.      * @throws HibernateException  
  110.      *             抛出Exception异常  
  111.      */   
  112.     void  save(E entity)  throws  HibernateException;  
  113.   
  114.     /**  
  115.      *   
  116.      * @param entity  
  117.      *            删除一个实体  
  118.      * @throws HibernateException  
  119.      *             抛出异常  
  120.      */   
  121.     void  delete(E entity)  throws  HibernateException;  
  122.   
  123.     /**  
  124.      *   
  125.      * @param entity  
  126.      *            删除一个实体  
  127.      * @param lock  
  128.      *            加锁实体  
  129.      * @throws HibernateException  
  130.      *             抛出异常  
  131.      */   
  132.     void  delete(E entity, LockMode lock)  throws  HibernateException;  
  133.   
  134.     /**  
  135.      *   
  136.      * @param entitys  
  137.      *            删除多个实体  
  138.      * @throws HibernateException  
  139.      *             抛出异常  
  140.      */   
  141.     void  delete(Collection<E> entitys)  throws  HibernateException;  
  142.   
  143.     /**  
  144.      *   
  145.      * @param entity  
  146.      *            修改一个实体  
  147.      * @throws HibernateException  
  148.      *             抛出异常  
  149.      */   
  150.     void  update(E entity)  throws  HibernateException;  
  151.   
  152.     /**  
  153.      *   
  154.      * @param entity  
  155.      *            修改一个实体  
  156.      * @param lock  
  157.      *            加锁实体  
  158.      * @throws HibernateException  
  159.      *             抛出异常  
  160.      */   
  161.     void  update(E entity, LockMode lock)  throws  HibernateException;  
  162.   
  163.     /**  
  164.      *   
  165.      * @param entity  
  166.      *            当实体在数据库不在在与之对应记录时,则保存实体,在在实体,则更新实体  
  167.      * @throws HibernateException  
  168.      *             抛出异常  
  169.      */   
  170.     void  saveOrUpdate(E entity)  throws  HibernateException;  
  171.   
  172.     /**  
  173.      *   
  174.      * @param entitys  
  175.      *            保存多个实体  
  176.      * @throws HibernateException  
  177.      *             抛出异常  
  178.      */   
  179.     void  saveOrUpdate(Collection<E> entitys)  throws  HibernateException;  
  180.   
  181.     /*---------------------------利用hql,sql对数据库进行操作 --------------------------------*/   
  182.   
  183.     /**  
  184.      *   
  185.      * @param hql  
  186.      *            使用hql语句进行数据库增删改操作  
  187.      * @return 受影响行的记录数  
  188.      */   
  189.     Integer bulkUpdate(String hql);  
  190.   
  191.     /**  
  192.      *   
  193.      * @param hql  
  194.      *            使用hql语句进行数据库增删改操作  
  195.      * @param params  
  196.      *            hql语句参数  
  197.      * @return 受影响行的记录数  
  198.      */   
  199.     Integer bulkUpdate(String hql, Object... values);  
  200.   
  201.     /**  
  202.      *   
  203.      * @param hql  
  204.      *            使用hql语句,检索数据  
  205.      * @return 一个list集合  
  206.      */   
  207.     List<E> find(String hql);  
  208.   
  209.     /**  
  210.      *   
  211.      * @param hql  
  212.      *            使用hql语句,检索数据  
  213.      * @param params  
  214.      *            hql语句参数  
  215.      * @return 一个list集合  
  216.      */   
  217.     List<E> find(String hql, Object... values);  
  218.   
  219.     /**  
  220.      *   
  221.      * @param queryName  
  222.      *            使用命名的hql语句进行查询  
  223.      * @return 一个list集合  
  224.      */   
  225.     List<E> findByNamedQuery(String queryName);  
  226.   
  227.     /**  
  228.      *   
  229.      * @param queryName  
  230.      *            使用带参数的命名hql语句进行查询  
  231.      * @param values  
  232.      *            参数集合  
  233.      * @return 一个list集合  
  234.      */   
  235.     List<E> findByNamedQuery(String queryName, Object... values);  
  236.   
  237.     /**  
  238.      *   
  239.      * @param queryName  
  240.      *            使用带参数的命名hql语句进行查询  
  241.      * @param params  
  242.      *            参数集合<br>  
  243.      *            Map的键为参数名称即paramName<br>  
  244.      *            Map的值则为values  
  245.      * @return 一个list集合  
  246.      */   
  247.     List<E> findByNamedParam(String queryName, Map<String, Object> params);  
  248.   
  249.     /**  
  250.      *   
  251.      * @param queryName  
  252.      *            使用带参数的命名hql语句进行查询  
  253.      * @param params  
  254.      *            参数集合<br>  
  255.      *            Map的键为参数名称即paramName<br>  
  256.      *            Map的值则为values  
  257.      * @return 一个list集合  
  258.      */   
  259.     List<E> findByNamedQueryAndNamedParam(String queryName,  
  260.             Map<String, Object> params);  
  261.   
  262.     /**  
  263.      *   
  264.      * @param criteria  
  265.      *            使 用指定的检索标准来检索数  
  266.      * @return 一个list集合  
  267.      */  
  268.     List<E> findByCriteria(DetachedCriteria criteria);  
  269.   
  270.     /**  
  271.      *   
  272.      * @param criteria  
  273.      *            使用指定的检索标准来分页检索数据  
  274.      * @param firstResult  
  275.      *            开始条数  
  276.      * @param maxResults  
  277.      *            返回记录数  
  278.      * @return 一个list集合  
  279.      */   
  280.     List<E> findByCriteria(DetachedCriteria criteria, Integer firstResult,  
  281.             Integer maxResults);  
  282.   
  283.     /**  
  284.      * 加 锁指定的实体  
  285.      *   
  286.      * @param entity  
  287.      *            实体对象  
  288.      *   
  289.      * @param lock  
  290.      *            加锁  
  291.      */   
  292.     void  lock(E entity, LockMode lock)  throws  HibernateException;  
  293.   
  294.     /**  
  295.      * 强 制立即更新到数据库,否则需要事务提交后,才会提交到数据库  
  296.      */   
  297.     void  flush()  throws  HibernateException;  
  298.   
  299.     /**  
  300.      *   
  301.      * @return 根据SimpleDao泛型类型,创建一个与会话无关的检索对象  
  302.      */   
  303.     DetachedCriteria createDetachedCriteria();  
  304.   
  305.     /**  
  306.      *   
  307.      * @param c  
  308.      *            为一个实体类型  
  309.      * @return 根据指定的类型创建一个与会话无关的检索对象  
  310.      */   
  311.     DetachedCriteria createDetachedCriteria(Class<? extends  Serializable> c);  
  312.   
  313.     /**  
  314.      *   
  315.      * @return 创建与会话绑定的检索标准对象  
  316.      */   
  317.     Criteria createCriteria();  
  318.   
  319. }  
/*
 * 
 * @author zyong
 *
 * @date 2009-9-19 下午11:02:34
 *
 * @action 一个简单公共的hibernate通用dao实现类
 */
package com.wind.dao;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.criterion.DetachedCriteria;

/**
 * 
 * @author zyong
 * 
 * @action 一个通用的Hibernate的dao接口<br>
 *         数据访问层里面的每一个接口都应该继承这个接口<br>
 *         而不用重写里面的方法
 */
public interface SimpleDao<E extends Serializable, PK extends Serializable> {

	/**
	 * 
	 * 该枚举类型用于,getStackValue方法中的Stack枚举
	 * 
	 */
	enum Stack {
		MAX, MIN, AVG, SUM;
	}

	/**
	 * 
	 * @param id
	 *            根据主键查询一个实体
	 * @return 一个实体对象
	 */
	E get(PK id);

	/**
	 * 
	 * @param id
	 *            根据主键查询一个实体
	 * @param lock
	 *            加锁实体
	 * @return 一个实体对象
	 */
	E get(PK id, LockMode lock);

	/**
	 * 使用数据库函数
	 * 
	 * @param criteria
	 *            一个DetacherCriteria对象
	 * @param propertyName
	 *            实体类属性名
	 * @param stackName
	 *            Stack枚举类型中的任意一个
	 * @return 一行一列数据库
	 */
	Object getStackValue(DetachedCriteria criteria, String propertyName,
			String stackName);

	/**
	 * 查询数据库对应的记录数
	 * 
	 * @param criteria
	 *            一个DetachedCriteria对象
	 * @return 记录数
	 */
	Integer getRowCount(DetachedCriteria criteria);

	/**
	 * 
	 * @param id
	 *            根据主键加裁一个实体对象
	 * @return 一个实体对象
	 */
	E load(PK id);

	/**
	 * 
	 * @param id
	 *            根据主键加裁实体
	 * @param lock
	 *            加锁实体
	 * @return 一个实体对象
	 */
	E load(PK id, LockMode lock);

	/**
	 * 
	 * @return 加裁所有对象
	 */
	List<E> loadAll();

	/**
	 * 
	 * @param entity
	 *            保存一个实体
	 * @throws HibernateException
	 *             抛出Exception异常
	 */
	void save(E entity) throws HibernateException;

	/**
	 * 
	 * @param entity
	 *            删除一个实体
	 * @throws HibernateException
	 *             抛出异常
	 */
	void delete(E entity) throws HibernateException;

	/**
	 * 
	 * @param entity
	 *            删除一个实体
	 * @param lock
	 *            加锁实体
	 * @throws HibernateException
	 *             抛出异常
	 */
	void delete(E entity, LockMode lock) throws HibernateException;

	/**
	 * 
	 * @param entitys
	 *            删除多个实体
	 * @throws HibernateException
	 *             抛出异常
	 */
	void delete(Collection<E> entitys) throws HibernateException;

	/**
	 * 
	 * @param entity
	 *            修改一个实体
	 * @throws HibernateException
	 *             抛出异常
	 */
	void update(E entity) throws HibernateException;

	/**
	 * 
	 * @param entity
	 *            修改一个实体
	 * @param lock
	 *            加锁实体
	 * @throws HibernateException
	 *             抛出异常
	 */
	void update(E entity, LockMode lock) throws HibernateException;

	/**
	 * 
	 * @param entity
	 *            当实体在数据库不在在与之对应记录时,则保存实体,在在实体,则更新实体
	 * @throws HibernateException
	 *             抛出异常
	 */
	void saveOrUpdate(E entity) throws HibernateException;

	/**
	 * 
	 * @param entitys
	 *            保存多个实体
	 * @throws HibernateException
	 *             抛出异常
	 */
	void saveOrUpdate(Collection<E> entitys) throws HibernateException;

	/*---------------------------利用hql,sql对数据库进行操作--------------------------------*/

	/**
	 * 
	 * @param hql
	 *            使用hql语句进行数据库增删改操作
	 * @return 受影响行的记录数
	 */
	Integer bulkUpdate(String hql);

	/**
	 * 
	 * @param hql
	 *            使用hql语句进行数据库增删改操作
	 * @param params
	 *            hql语句参数
	 * @return 受影响行的记录数
	 */
	Integer bulkUpdate(String hql, Object... values);

	/**
	 * 
	 * @param hql
	 *            使用hql语句,检索数据
	 * @return 一个list集合
	 */
	List<E> find(String hql);

	/**
	 * 
	 * @param hql
	 *            使用hql语句,检索数据
	 * @param params
	 *            hql语句参数
	 * @return 一个list集合
	 */
	List<E> find(String hql, Object... values);

	/**
	 * 
	 * @param queryName
	 *            使用命名的hql语句进行查询
	 * @return 一个list集合
	 */
	List<E> findByNamedQuery(String queryName);

	/**
	 * 
	 * @param queryName
	 *            使用带参数的命名hql语句进行查询
	 * @param values
	 *            参数集合
	 * @return 一个list集合
	 */
	List<E> findByNamedQuery(String queryName, Object... values);

	/**
	 * 
	 * @param queryName
	 *            使用带参数的命名hql语句进行查询
	 * @param params
	 *            参数集合<br>
	 *            Map的键为参数名称即paramName<br>
	 *            Map的值则为values
	 * @return 一个list集合
	 */
	List<E> findByNamedParam(String queryName, Map<String, Object> params);

	/**
	 * 
	 * @param queryName
	 *            使用带参数的命名hql语句进行查询
	 * @param params
	 *            参数集合<br>
	 *            Map的键为参数名称即paramName<br>
	 *            Map的值则为values
	 * @return 一个list集合
	 */
	List<E> findByNamedQueryAndNamedParam(String queryName,
			Map<String, Object> params);

	/**
	 * 
	 * @param criteria
	 *            使用指定的检索标准来检索数
	 * @return 一个list集合
	 */
	List<E> findByCriteria(DetachedCriteria criteria);

	/**
	 * 
	 * @param criteria
	 *            使用指定的检索标准来分页检索数据
	 * @param firstResult
	 *            开始条数
	 * @param maxResults
	 *            返回记录数
	 * @return 一个list集合
	 */
	List<E> findByCriteria(DetachedCriteria criteria, Integer firstResult,
			Integer maxResults);

	/**
	 * 加锁指定的实体
	 * 
	 * @param entity
	 *            实体对象
	 * 
	 * @param lock
	 *            加锁
	 */
	void lock(E entity, LockMode lock) throws HibernateException;

	/**
	 * 强制立即更新到数据库,否则需要事务提交后,才会提交到数据库
	 */
	void flush() throws HibernateException;

	/**
	 * 
	 * @return 根据SimpleDao泛型类型,创建一个与会话无关的检索对象
	 */
	DetachedCriteria createDetachedCriteria();

	/**
	 * 
	 * @param c
	 *            为一个实体类型
	 * @return 根据指定的类型创建一个与会话无关的检索对象
	 */
	DetachedCriteria createDetachedCriteria(Class<? extends Serializable> c);

	/**
	 * 
	 * @return 创建与会话绑定的检索标准对象
	 */
	Criteria createCriteria();

}

 

SimpleDaoImpl为一个SimpleDao的实现类.代码如下:

Java代码
  1. /*  
  2.  *   
  3.  * @author zyong  
  4.  *  
  5.  * @date 2009-9-19 下 午11:02:34  
  6.  *  
  7.  * @action 一个简单公共的hibernate通用dao实现类  
  8.  */   
  9. package  com.wind.dao.impl;  
  10.   
  11. import  java.io.Serializable;  
  12. import  java.lang.reflect.ParameterizedType;  
  13. import  java.lang.reflect.Type;  
  14. import  java.util.Collection;  
  15. import  java.util.List;  
  16. import  java.util.Map;  
  17.   
  18. import  org.hibernate.Criteria;  
  19. import  org.hibernate.HibernateException;  
  20. import  org.hibernate.LockMode;  
  21. import  org.hibernate.criterion.DetachedCriteria;  
  22. import  org.hibernate.criterion.Projections;  
  23. import  org.springframework.orm.hibernate3.support.HibernateDaoSupport;  
  24.   
  25. import  com.wind.dao.SimpleDao;  
  26.   
  27. /**  
  28.  *   
  29.  * @author zyong  
  30.  *   
  31.  * @action 一 个公共的Hibernate通用dao实现类<br>  
  32.  *         数据库访问层,每一个实现类都应该来继承该类<br>  
  33.  *         不应该重写里面的方法,需要相应的方法,直接到数据访问层每个类对应的接口中添加  
  34.  */   
  35. public   abstract   class  SimpleDaoImpl<E  extends  Serializable, PK  extends  Serializable>  
  36.         extends  HibernateDaoSupport  implements  SimpleDao<E, PK> {  
  37.   
  38.     /**  
  39.      * 为 E对应的实例类型  
  40.      */   
  41.     private  Class<?> entityClass;  
  42.   
  43.     /**  
  44.      * 获 取E实例类的类型  
  45.      */   
  46.     public  SimpleDaoImpl() {  
  47.         Class<?> c = this .getClass();  
  48.         Type t = c.getGenericSuperclass();  
  49.         if  (t  instanceof  ParameterizedType) {  
  50.             this .entityClass = (Class<?>) ((ParameterizedType) t)  
  51.                     .getActualTypeArguments()[0 ];  
  52.         }  
  53.     }  
  54.   
  55.     @SuppressWarnings ( "unchecked" )  
  56.     public  E get(PK id) {  
  57.         return  (E)  this .getHibernateTemplate().get( this .entityClass, id);  
  58.     }  
  59.   
  60.     @SuppressWarnings ( "unchecked" )  
  61.     public  E get(PK id, LockMode lock) {  
  62.         E entity = (E) this .getHibernateTemplate().get( this .entityClass, id,  
  63.                 lock);  
  64.         if  (entity !=  null ) {  
  65.             this .flush(); // 如 果实体不为null,立即刷新,否则锁不会生效   
  66.         }  
  67.         return  entity;  
  68.     }  
  69.   
  70.     public  Object getStackValue(DetachedCriteria criteria, String propertyName,  
  71.             Stack value) {  
  72.         switch  (value) {  
  73.         case  MAX:  
  74.             criteria.setProjection(Projections.max(propertyName));  
  75.             break ;  
  76.         case  MIN:  
  77.             criteria.setProjection(Projections.min(propertyName));  
  78.             break ;  
  79.         case  AVG:  
  80.             criteria.setProjection(Projections.avg(propertyName));  
  81.             break ;  
  82.         default :  
  83.             criteria.setProjection(Projections.sum(propertyName));  
  84.             break ;  
  85.         }  
  86.         return   this .findByCriteria(criteria,  01 ).get( 0 );  
  87.     }  
  88.   
  89.     public  Integer getRowCount(DetachedCriteria criteria) {  
  90.         criteria.setProjection(Projections.rowCount());  
  91.         return  (Integer)  this .findByCriteria(criteria,  01 ).get( 0 );  
  92.     }  
  93.   
  94.     @SuppressWarnings ( "unchecked" )  
  95.     public  E load(PK id) {  
  96.         return  (E)  this .getHibernateTemplate().load( this .entityClass, id);  
  97.     }  
  98.   
  99.     @SuppressWarnings ( "unchecked" )  
  100.     public  E load(PK id, LockMode lock) {  
  101.         E entity = (E) this .getHibernateTemplate().load( this .entityClass, id,  
  102.                 lock);  
  103.         if  (entity !=  null ) {  
  104.             this .flush(); // 如 果实体不为null,立即刷新,否则锁不会生效   
  105.         }  
  106.         return  entity;  
  107.     }  
  108.   
  109.     @SuppressWarnings ( "unchecked" )  
  110.     public  List<E> loadAll() {  
  111.         return   this .getHibernateTemplate().loadAll(entityClass);  
  112.     }  
  113.   
  114.     @SuppressWarnings ( "unchecked" )  
  115.     public  List<E> find(String hql) {  
  116.         return   this .getHibernateTemplate().find(hql);  
  117.     }  
  118.   
  119.     @SuppressWarnings ( "unchecked" )  
  120.     public  List<E> find(String hql, Object... values) {  
  121.         return   this .getHibernateTemplate().find(hql, values);  
  122.     }  
  123.   
  124.     @SuppressWarnings ( "unchecked" )  
  125.     public  List<E> findByNamedQuery(String queryName, Object... values) {  
  126.         return   this .getHibernateTemplate().findByNamedQuery(queryName, values);  
  127.     }  
  128.   
  129.     @SuppressWarnings ( "unchecked" )  
  130.     public  List<E> findByNamedQuery(String queryName) {  
  131.         return   this .getHibernateTemplate().findByNamedQuery(queryName);  
  132.     }  
  133.   
  134.     @SuppressWarnings ( "unchecked" )  
  135.     public  List<E> findByNamedQueryAndNamedParam(String queryName,  
  136.             Map<String, Object> params) {  
  137.         return   this .getHibernateTemplate().findByNamedQueryAndNamedParam(  
  138.                 queryName, (String[]) params.keySet().toArray(),  
  139.                 params.values().toArray());  
  140.     }  
  141.   
  142.     @SuppressWarnings ( "unchecked" )  
  143.     public  List<E> findByNamedParam(String queryName, Map<String, Object> params) {  
  144.         return   this .getHibernateTemplate()  
  145.                 .findByNamedParam(queryName,  
  146.                         (String[]) params.keySet().toArray(),  
  147.                         params.values().toArray());  
  148.     }  
  149.   
  150.     @SuppressWarnings ( "unchecked" )  
  151.     public  List<E> findByCriteria(DetachedCriteria criteria) {  
  152.         return   this .getHibernateTemplate().findByCriteria(criteria);  
  153.     }  
  154.   
  155.     @SuppressWarnings ( "unchecked" )  
  156.     public  List<E> findByCriteria(DetachedCriteria criteria,  
  157.             Integer firstResult, Integer maxResults) {  
  158.         return   this .getHibernateTemplate().findByCriteria(criteria,  
  159.                 firstResult, maxResults);  
  160.     }  
  161.   
  162.     public   void  save(E entity)  throws  HibernateException {  
  163.         this .getHibernateTemplate().save(entity);  
  164.     }  
  165.   
  166.     public   void  saveOrUpdate(E entity)  throws  HibernateException {  
  167.         this .getHibernateTemplate().saveOrUpdate(entity);  
  168.     }  
  169.   
  170.     public   void  saveOrUpdate(Collection<E> entitys)  throws  HibernateException {  
  171.         this .getHibernateTemplate().saveOrUpdateAll(entitys);  
  172.     }  
  173.   
  174.     public   void  delete(E entity)  throws  HibernateException {  
  175.         this .getHibernateTemplate().delete(entity);  
  176.     }  
  177.   
  178.     public   void  delete(E entity, LockMode lock)  throws  HibernateException {  
  179.         this .getHibernateTemplate().delete(entity, lock);  
  180.         this .flush(); // 如 果实体不为null,立即刷新,否则锁不会生效   
  181.     }  
  182.   
  183.     public   void  delete(Collection<E> entitys)  throws  HibernateException {  
  184.         this .getHibernateTemplate().deleteAll(entitys);  
  185.     }  
  186.   
  187.     public   void  update(E entity)  throws  HibernateException {  
  188.         this .getHibernateTemplate().update(entity);  
  189.     }  
  190.   
  191.     public   void  update(E entity, LockMode lock)  throws  HibernateException {  
  192.         this .getHibernateTemplate().update(entity, lock);  
  193.         this .flush(); // 如 果实体不为null,立即刷新,否则锁不会生效   
  194.     }  
  195.   
  196.     public  Integer bulkUpdate(String hql) {  
  197.         return   this .getHibernateTemplate().bulkUpdate(hql);  
  198.     }  
  199.   
  200.     public  Integer bulkUpdate(String hql, Object... values) {  
  201.         return   this .getHibernateTemplate().bulkUpdate(hql, values);  
  202.     }  
  203.   
  204.     public   void  flush()  throws  HibernateException {  
  205.         this .getHibernateTemplate().flush();  
  206.     }  
  207.   
  208.     public   void  lock(E entity, LockMode lock)  throws  HibernateException {  
  209.         this .getHibernateTemplate().lock(entity, lock);  
  210.     }  
  211.   
  212.     public  DetachedCriteria createDetachedCriteria() {  
  213.         return  DetachedCriteria.forClass( this .entityClass);  
  214.     }  
  215.   
  216.     public  DetachedCriteria createDetachedCriteria(  
  217.             Class<? extends  Serializable> c) {  
  218.         return  DetachedCriteria.forClass(c);  
  219.     }  
  220.   
  221.     public  Criteria createCriteria() {  
  222.         return   this .createDetachedCriteria().getExecutableCriteria(  
  223.                 this .getSession());  
  224.     }  
  225.   
  226. }  
/*
 * 
 * @author zyong
 *
 * @date 2009-9-19 下午11:02:34
 *
 * @action 一个简单公共的hibernate通用dao实现类
 */
package com.wind.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.wind.dao.SimpleDao;

/**
 * 
 * @author zyong
 * 
 * @action 一个公共的Hibernate通用dao实现类<br>
 *         数据库访问层,每一个实现类都应该来继承该类<br>
 *         不应该重写里面的方法,需要相应的方法,直接到数据访问层每个类对应的接口中添加
 */
public abstract class SimpleDaoImpl<E extends Serializable, PK extends Serializable>
		extends HibernateDaoSupport implements SimpleDao<E, PK> {

	/**
	 * 为E对应的实例类型
	 */
	private Class<?> entityClass;

	/**
	 * 获取E实例类的类型
	 */
	public SimpleDaoImpl() {
		Class<?> c = this.getClass();
		Type t = c.getGenericSuperclass();
		if (t instanceof ParameterizedType) {
			this.entityClass = (Class<?>) ((ParameterizedType) t)
					.getActualTypeArguments()[0];
		}
	}

	@SuppressWarnings("unchecked")
	public E get(PK id) {
		return (E) this.getHibernateTemplate().get(this.entityClass, id);
	}

	@SuppressWarnings("unchecked")
	public E get(PK id, LockMode lock) {
		E entity = (E) this.getHibernateTemplate().get(this.entityClass, id,
				lock);
		if (entity != null) {
			this.flush();// 如果实体不为null,立即刷新,否则锁不会生效
		}
		return entity;
	}

	public Object getStackValue(DetachedCriteria criteria, String propertyName,
			Stack value) {
		switch (value) {
		case MAX:
			criteria.setProjection(Projections.max(propertyName));
			break;
		case MIN:
			criteria.setProjection(Projections.min(propertyName));
			break;
		case AVG:
			criteria.setProjection(Projections.avg(propertyName));
			break;
		default:
			criteria.setProjection(Projections.sum(propertyName));
			break;
		}
		return this.findByCriteria(criteria, 0, 1).get(0);
	}

	public Integer getRowCount(DetachedCriteria criteria) {
		criteria.setProjection(Projections.rowCount());
		return (Integer) this.findByCriteria(criteria, 0, 1).get(0);
	}

	@SuppressWarnings("unchecked")
	public E load(PK id) {
		return (E) this.getHibernateTemplate().load(this.entityClass, id);
	}

	@SuppressWarnings("unchecked")
	public E load(PK id, LockMode lock) {
		E entity = (E) this.getHibernateTemplate().load(this.entityClass, id,
				lock);
		if (entity != null) {
			this.flush();// 如果实体不为null,立即刷新,否则锁不会生效
		}
		return entity;
	}

	@SuppressWarnings("unchecked")
	public List<E> loadAll() {
		return this.getHibernateTemplate().loadAll(entityClass);
	}

	@SuppressWarnings("unchecked")
	public List<E> find(String hql) {
		return this.getHibernateTemplate().find(hql);
	}

	@SuppressWarnings("unchecked")
	public List<E> find(String hql, Object... values) {
		return this.getHibernateTemplate().find(hql, values);
	}

	@SuppressWarnings("unchecked")
	public List<E> findByNamedQuery(String queryName, Object... values) {
		return this.getHibernateTemplate().findByNamedQuery(queryName, values);
	}

	@SuppressWarnings("unchecked")
	public List<E> findByNamedQuery(String queryName) {
		return this.getHibernateTemplate().findByNamedQuery(queryName);
	}

	@SuppressWarnings("unchecked")
	public List<E> findByNamedQueryAndNamedParam(String queryName,
			Map<String, Object> params) {
		return this.getHibernateTemplate().findByNamedQueryAndNamedParam(
				queryName, (String[]) params.keySet().toArray(),
				params.values().toArray());
	}

	@SuppressWarnings("unchecked")
	public List<E> findByNamedParam(String queryName, Map<String, Object> params) {
		return this.getHibernateTemplate()
				.findByNamedParam(queryName,
						(String[]) params.keySet().toArray(),
						params.values().toArray());
	}

	@SuppressWarnings("unchecked")
	public List<E> findByCriteria(DetachedCriteria criteria) {
		return this.getHibernateTemplate().findByCriteria(criteria);
	}

	@SuppressWarnings("unchecked")
	public List<E> findByCriteria(DetachedCriteria criteria,
			Integer firstResult, Integer maxResults) {
		return this.getHibernateTemplate().findByCriteria(criteria,
				firstResult, maxResults);
	}

	public void save(E entity) throws HibernateException {
		this.getHibernateTemplate().save(entity);
	}

	public void saveOrUpdate(E entity) throws HibernateException {
		this.getHibernateTemplate().saveOrUpdate(entity);
	}

	public void saveOrUpdate(Collection<E> entitys) throws HibernateException {
		this.getHibernateTemplate().saveOrUpdateAll(entitys);
	}

	public void delete(E entity) throws HibernateException {
		this.getHibernateTemplate().delete(entity);
	}

	public void delete(E entity, LockMode lock) throws HibernateException {
		this.getHibernateTemplate().delete(entity, lock);
		this.flush();// 如果实体不为null,立即刷新,否则锁不会生效
	}

	public void delete(Collection<E> entitys) throws HibernateException {
		this.getHibernateTemplate().deleteAll(entitys);
	}

	public void update(E entity) throws HibernateException {
		this.getHibernateTemplate().update(entity);
	}

	public void update(E entity, LockMode lock) throws HibernateException {
		this.getHibernateTemplate().update(entity, lock);
		this.flush();// 如果实体不为null,立即刷新,否则锁不会生效
	}

	public Integer bulkUpdate(String hql) {
		return this.getHibernateTemplate().bulkUpdate(hql);
	}

	public Integer bulkUpdate(String hql, Object... values) {
		return this.getHibernateTemplate().bulkUpdate(hql, values);
	}

	public void flush() throws HibernateException {
		this.getHibernateTemplate().flush();
	}

	public void lock(E entity, LockMode lock) throws HibernateException {
		this.getHibernateTemplate().lock(entity, lock);
	}

	public DetachedCriteria createDetachedCriteria() {
		return DetachedCriteria.forClass(this.entityClass);
	}

	public DetachedCriteria createDetachedCriteria(
			Class<? extends Serializable> c) {
		return DetachedCriteria.forClass(c);
	}

	public Criteria createCriteria() {
		return this.createDetachedCriteria().getExecutableCriteria(
				this.getSession());
	}

}

 

 

数据访问层里面的每一个接口都继承SimpleDao接口,每一个接口的实现类都继承SimpleDaoImpl类.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值