hibernate 泛型 DAO

来源:互联网 发布:张博士医考网络课登陆 编辑:程序博客网 时间:2024/05/16 06:00
 Data Access Object (DAO) 是一般的J2EE项目中的一个常见的模块,在我们用一般的方法去实现DAO的过程中会发现在为每个pojo实现DAO的的时候会不断地区重复的写一些常用的方法,如update(),delete(),find()等。 
     
    为了解决以上所述的缺点,可以采用DAO用泛型实现的方法,把通用的方法抽出来放到基类中,以后为pojo实现DAO的时候只要继承DAO基类就可以复用这些通用方法。这样的做法即保证了代码的复用,又保证了类型的安全。 

下面例子为以前一个项目中的代码片段: 
代码说明: 
IBaseDao          是DAO基类的接口 
BaseHibernateDao  是DAO的Hibernate实现基类(实现了接口IBaseDao) 
IUserDao          是具体的DAO接口,用于持久化用户数据(继承了接口IBaseDao) 
UserHibernateDao  是具体的DAO的Hibernate实现,持久化用户数据(继承了BaseHibernate 并实现了接口 IUserDao) 

UserHibernateDao 继承了BaseHibernateDao的所有功能,在新建一个DAO时 
只要用 XxxxxHibernateDao extends BaseHibernate就可以继承BaseHibernate的所有功能。 


1.DAO基类接口
 
Java代码  收藏代码
  1. package com.rc.video.common.base;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.List;  
  5.   
  6. import com.rc.video.pojo.TVideo;  
  7.   
  8. /** 
  9.  * DAO 基类接口 
  10.  * @param <T> T pojo类型 
  11.  * @param <ID> ID类型 
  12.  */  
  13. public interface IBaseDao<T,ID extends Serializable>  
  14. {  
  15.       
  16.   
  17.     public abstract List<T> findAll();  
  18.       
  19.     /** 
  20.      * 查找所有,并分页 
  21.      * @param page     要返回的页数 
  22.      * @param pageSize 没有记录数 
  23.      * @return 
  24.      */  
  25.     public abstract List<T> findAll(int page, int pageSize);  
  26.       
  27.     public abstract void save(T entity);  
  28.       
  29.     public abstract void delete(T entity);  
  30.       
  31.     /** 
  32.      * 与findByProperty相似,当properyName == value 时把相应的记录删除 
  33.      */  
  34.     public abstract void deleteByProperty(String propertyName, Object value);  
  35.       
  36.     public abstract List<T> findByExample(T example);  
  37.       
  38.     /** 
  39.      * 通过属性查找 
  40.      * @param   propertyName    属性名称 
  41.      * @param   value           属性的值 
  42.      * @return 
  43.      */  
  44.     public abstract List<T> findByProperty(String propertyName, Object value);  
  45.       
  46.   
  47.       
  48.     /** 
  49.      * 通过多个属性查找 
  50.      * @param   propertyNames   属性名称数组 
  51.      * @param   values          属性值数组 
  52.      * @return 
  53.      */  
  54.     public abstract List<T> findByPropertys(String[] propertyNames,Object[] values);  
  55.       
  56.     /** 
  57.      * 通过多个属性查找,并分页, 
  58.      * 属性名称数组和属性值数组的序列要对应 
  59.      *  
  60.      * @param   propertyNames   属性名称数组 
  61.      * @param   values          属性值数组 
  62.      * @param   page            页码 
  63.      * @param   pageSize        每页内容条数 
  64.      * @return 
  65.      */  
  66.     public List<T> findByPropertys(String[] propertyNames,Object[] values,int page,int pageSize);  
  67.       
  68.     /** 
  69.      * 通过属性查找,并分页, 
  70.      * 属性名称数组和属性值数组的序列要对应 
  71.      *  
  72.      * @param   propertyNames   属性名称 
  73.      * @param   values          属性值 
  74.      * @param   page            页码 
  75.      * @param   pageSize        每页内容条数 
  76.      * @return 
  77.      */  
  78.     public List<T> findByProperty(String propertyName,Object value,int page,int pageSize);  
  79.       
  80.     /** 
  81.      * 统计所有记录的总数 
  82.      * @return 总数 
  83.      */  
  84.     public int countAll();  
  85.     /** 
  86.      * 统计数据库中当propertyName=value时的记录总数 
  87.      * @param propertyName 
  88.      * @param value 
  89.      * @return 
  90.      */  
  91.     public int countByProperty(String propertyName, Object value);  
  92.     /** 
  93.      *  统计数据库中当多个propertyName=value时的记录总数 
  94.      * @param propertyNames  
  95.      * @param values 
  96.      * @return 
  97.      */   
  98.     public int countByPropertys(String[] propertyNames, Object[] values);  
  99.       
  100.     public abstract void saveOrUpdate(T entity);  
  101.       
  102.     public abstract T findById(ID id);  
  103.       
  104.     public abstract void update(T entity);  
  105.       
  106.       
  107.     /** 
  108.      * 获得持久化对象的类型 
  109.      * @return 
  110.      */  
  111.     public abstract Class<T> getPersistentClass();  
  112.       
  113.     /** 
  114.      * 查找并通过某一属性排序 
  115.      * @param property 排序依据的顺序 
  116.      * @param isSequence    是否顺序排序 
  117.      */  
  118.     public List<T> findAndOrderByProperty(int firstResult, int fetchSize, String propertyName, boolean isSequence);  
  119.       
  120.       
  121.     /** 
  122.      * 查找并通过某一属性排序 
  123.      * @param property 排序依据的顺序 
  124.      * @param isSequence    是否顺序排序 
  125.      */  
  126.     public List<T> findAllAndOrderByProperty(String propertyName, boolean isSequence);  
  127.       
  128.       
  129. }  


2.DAO的Hibernate基类 
Java代码  收藏代码
  1. package com.rc.video.common.base;  
  2.   
  3. import java.io.Serializable;  
  4. import java.lang.reflect.ParameterizedType;  
  5. import java.util.List;  
  6.   
  7. import org.hibernate.Query;  
  8. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;  
  9.   
  10. /** 
  11.  * DAO的Hibernate基类 
  12.  * @author pasu 
  13.  * @param <T> 
  14.  *            pojo的类型 
  15.  * @para <ID> id的类型 
  16.  *  
  17.  */  
  18. public abstract class BaseHibernateDao<T, ID extends Serializable> extends  
  19.         HibernateDaoSupport implements IBaseDao<T, ID>  
  20. {  
  21.     private Class<T> persistentClass;  
  22.   
  23.     @SuppressWarnings("unchecked")  
  24.     public BaseHibernateDao()  
  25.     {  
  26.         // 获取持久化对象的类型  
  27.         this.persistentClass = (Class<T>) ((ParameterizedType) getClass()  
  28.                 .getGenericSuperclass()).getActualTypeArguments()[0];  
  29.     }  
  30.   
  31.     public Class<T> getPersistentClass()  
  32.     {  
  33.         return persistentClass;  
  34.     }  
  35.   
  36.     /** 
  37.      * 通过id查找 
  38.      *  
  39.      * @param id 
  40.      * @return 
  41.      */  
  42.     @SuppressWarnings("unchecked")  
  43.     public T findById(ID id)  
  44.     {  
  45.         return (T) this.getHibernateTemplate().get(getPersistentClass(), id);  
  46.     }  
  47.   
  48.     public void save(T entity)  
  49.     {  
  50.         this.getHibernateTemplate().save(entity);  
  51.     }  
  52.   
  53.     /** 
  54.      * 删除 
  55.      */  
  56.     public void delete(T entity)  
  57.     {  
  58.         this.getHibernateTemplate().delete(entity);  
  59.     }  
  60.   
  61.     /** 
  62.      * 通过属性删除 
  63.      */  
  64.     public void deleteByProperty(String propertyName, Object value)  
  65.     {  
  66.         String queryString = "delete from " + getPersistentClass().getName()  
  67.                 + " as model where model." + propertyName + "= ?";  
  68.         Query query = this.getSession().createQuery(queryString);  
  69.         query.setParameter(0, value);  
  70.         query.executeUpdate();  
  71.     }  
  72.   
  73.     /** 
  74.      * saveOrUpdate 
  75.      */  
  76.     public void saveOrUpdate(T entity)  
  77.     {  
  78.         this.getHibernateTemplate().saveOrUpdate(entity);  
  79.     }  
  80.   
  81.     /** 
  82.      * 更新 
  83.      */  
  84.     public void update(T entity)  
  85.     {  
  86.         this.getHibernateTemplate().update(entity);  
  87.     }  
  88.   
  89.     /** 
  90.      * 分页查找所有的记录 
  91.      *  
  92.      * @param page 
  93.      *            要返回的页数 
  94.      * @param pageSize 
  95.      *            没有记录数 
  96.      * @return 
  97.      */  
  98.     public List<T> findAll(int page, int pageSize)  
  99.     {  
  100.         String queryString = "from " + getPersistentClass().getName();  
  101.         Query query = this.getSession().createQuery(queryString);  
  102.         int firstResult = (page - 1) * pageSize;  
  103.         query.setFirstResult(firstResult);  
  104.         query.setMaxResults(pageSize);  
  105.         return query.list();  
  106.     }  
  107.   
  108.     /** 
  109.      * 统计所有记录的总数 
  110.      *  
  111.      * @return 总数 
  112.      */  
  113.     public int countAll()  
  114.     {  
  115.         String queryString = "select count(*) from "  
  116.                 + getPersistentClass().getName();  
  117.         Query query = this.getSession().createQuery(queryString);  
  118.         List list = query.list();  
  119.         Long result = (Long) list.get(0);  
  120.         return result.intValue();  
  121.     }  
  122.   
  123.     /** 
  124.      * find By Example 
  125.      *  
  126.      * @param entity 
  127.      * @return 
  128.      */  
  129.     @SuppressWarnings("unchecked")  
  130.     public List<T> findByExample(T entity)  
  131.     {  
  132.         return this.getHibernateTemplate().findByExample(entity);  
  133.     }  
  134.   
  135.     @SuppressWarnings("unchecked")  
  136.     public List<T> findAll()  
  137.     {  
  138.         return this.getHibernateTemplate().find(  
  139.                 "from " + getPersistentClass().getName());  
  140.     }  
  141.   
  142.     /** 
  143.      * 通过属性查找 
  144.      *  
  145.      * @param propertyName 
  146.      *            属性名称 
  147.      * @param value 
  148.      *            属性的值 
  149.      * @return 
  150.      */  
  151.     @SuppressWarnings("unchecked")  
  152.     public List<T> findByProperty(String propertyName, Object value)  
  153.     {  
  154.         String queryString = "from " + getPersistentClass().getName()  
  155.                 + " as model where model." + propertyName + "= ?";  
  156.         return this.getHibernateTemplate().find(queryString, value);  
  157.   
  158.     }  
  159.   
  160.     /** 
  161.      * 通过多个属性组合查询 
  162.      *  
  163.      * @param propertyNames 
  164.      *            属性名称数组 
  165.      * @param values 
  166.      *            对应于propertyNames的值 return 匹配的结果 
  167.      */  
  168.     public List<T> findByPropertys(String[] propertyNames, Object[] values)  
  169.     {  
  170.         StringBuffer strBuffer = new StringBuffer();  
  171.         strBuffer.append("from " + getPersistentClass().getName());  
  172.         strBuffer.append(" as model where ");  
  173.         for (int i = 0; i < propertyNames.length; i++)  
  174.         {  
  175.             if (i != 0)  
  176.                 strBuffer.append(" and");  
  177.             strBuffer.append(" model.");  
  178.             strBuffer.append(propertyNames[i]);  
  179.             strBuffer.append("=");  
  180.             strBuffer.append("? ");  
  181.         }  
  182.         String queryString = strBuffer.toString();  
  183.         return this.getHibernateTemplate().find(queryString, values);  
  184.     }  
  185.   
  186.     /** 
  187.      * 通过属性查找并分页 
  188.      *  
  189.      * @param propertyName 
  190.      *            属性名称 
  191.      * @param value 
  192.      *            属性值 
  193.      * @param page 
  194.      *            页数 
  195.      * @param pageSize 
  196.      *            每页显示条数 
  197.      */  
  198.     public List<T> findByProperty(String propertyName, Object value, int page,  
  199.             int pageSize)  
  200.     {  
  201.         return this.findByPropertys(new String[]  
  202.         {  
  203.             propertyName  
  204.         }, new Object[]  
  205.         {  
  206.             value  
  207.         }, page, pageSize);  
  208.     }  
  209.   
  210.     /** 
  211.      * 通过多个属性组合查询 
  212.      *  
  213.      * @param propertyNames 
  214.      *            属性名称数组 
  215.      * @param values 
  216.      *            对应于propertyNames的值 
  217.      * @param page 
  218.      *            页数 
  219.      * @param pageSize 
  220.      *            每页显示数 return 匹配的结果 return 匹配的结果 
  221.      */  
  222.     public List<T> findByPropertys(String[] propertyNames, Object[] values,  
  223.             int page, int pageSize)  
  224.     {  
  225.   
  226.         StringBuffer strBuffer = new StringBuffer();  
  227.         strBuffer.append("from " + getPersistentClass().getName());  
  228.         strBuffer.append(" as model where ");  
  229.         for (int i = 0; i < propertyNames.length; i++)  
  230.         {  
  231.             if (i != 0)  
  232.                 strBuffer.append(" and");  
  233.             strBuffer.append(" model.");  
  234.             strBuffer.append(propertyNames[i]);  
  235.             strBuffer.append("=");  
  236.             strBuffer.append("? ");  
  237.         }  
  238.         String queryString = strBuffer.toString();  
  239.   
  240.         int firstResult = (page - 1) * pageSize;  
  241.   
  242.         Query query = this.getSession().createQuery(queryString);  
  243.         query.setFirstResult(firstResult);  
  244.         query.setMaxResults(pageSize);  
  245.         for (int i = 0; i < values.length; i++)  
  246.         {  
  247.             query.setParameter(i, values[i]);  
  248.         }  
  249.   
  250.         return query.list();  
  251.     }  
  252.   
  253.     /** 
  254.      * 通过属性统计数量 
  255.      *  
  256.      * @param propertyName 
  257.      *            属性名称 
  258.      * @param value 
  259.      *            属性值 
  260.      */  
  261.     public int countByProperty(String propertyName, Object value)  
  262.     {  
  263.         String[] propertyNames = new String[]  
  264.         {  
  265.             propertyName  
  266.         };  
  267.         Object[] values = new Object[]  
  268.         {  
  269.             value  
  270.         };  
  271.         return this.countByPropertys(propertyNames, values);  
  272.     }  
  273.   
  274.     /** 
  275.      * 通过多个属性统计数量 
  276.      *  
  277.      * @param propertyNames 
  278.      *            属性名称数组 
  279.      * @param values 
  280.      *            对应的属性值数组 return 
  281.      */  
  282.     public int countByPropertys(String[] propertyNames, Object[] values)  
  283.     {  
  284.         StringBuffer strBuffer = new StringBuffer();  
  285.         strBuffer.append("select count(*) from "  
  286.                 + getPersistentClass().getName());  
  287.         strBuffer.append(" as model where ");  
  288.         for (int i = 0; i < propertyNames.length; i++)  
  289.         {  
  290.             if (i != 0)  
  291.                 strBuffer.append(" and");  
  292.             strBuffer.append(" model.");  
  293.             strBuffer.append(propertyNames[i]);  
  294.             strBuffer.append("=");  
  295.             strBuffer.append("? ");  
  296.         }  
  297.   
  298.         String queryString = strBuffer.toString();  
  299.         Query query = this.getSession().createQuery(queryString);  
  300.         for (int i = 0; i < values.length; i++)  
  301.         {  
  302.             query.setParameter(i, values[i]);  
  303.         }  
  304.   
  305.         List list = query.list();  
  306.         Long result = (Long) list.get(0);  
  307.         return result.intValue();  
  308.     }  
  309.   
  310.     /** 
  311.      * 查找T并通过某一属性排序 
  312.      *  
  313.      * @param property 
  314.      *            排序依据的顺序 
  315.      * @param isSequence 
  316.      *            是否顺序排序,false为倒序 
  317.      */  
  318.     public List<T> findAndOrderByProperty(int firstResult, int fetchSize,  
  319.             String propertyName, boolean isSequence)  
  320.     {  
  321.         String queryString = "from " + getPersistentClass().getName()  
  322.                 + " as model order by model." + propertyName;  
  323.         if (isSequence == false)  
  324.         {  
  325.             queryString = queryString + " DESC";  
  326.         }  
  327.   
  328.         Query queryObject = getSession().createQuery(queryString);  
  329.         queryObject.setFirstResult(firstResult);  
  330.         queryObject.setMaxResults(fetchSize);  
  331.         return queryObject.list();  
  332.   
  333.     }  
  334.   
  335.     /** 
  336.      * 查找所有并通过某个属性排序 
  337.      *  
  338.      * @param propertyName 
  339.      *            排序依据的属性名称 
  340.      * @param isSequence 
  341.      *            是否顺序排列 
  342.      */  
  343.     public List<T> findAllAndOrderByProperty(String propertyName,  
  344.             boolean isSequence)  
  345.     {  
  346.         String queryString = "from " + getPersistentClass().getName()  
  347.                 + " as model order by model." + propertyName;  
  348.         if (isSequence == false)  
  349.         {  
  350.             queryString = queryString + " DESC";  
  351.         }  
  352.   
  353.         Query queryObject = getSession().createQuery(queryString);  
  354.         return queryObject.list();  
  355.     }  
  356.   
  357. }  


3.具体的DAO接口(继承IBaseDao): 
Java代码  收藏代码
  1. package com.rc.video.dao;  
  2.   
  3. import com.rc.video.common.base.IBaseDao;  
  4. import com.rc.video.pojo.TUser;  
  5.   
  6. /** 
  7.  * 用户Dao 
  8.  *  
  9.  * @author pasu 
  10.  * @see com.rc.video.common.base.IBaseDao 
  11.  *  @vesion 1.0, 2008-3-2 
  12.  */  
  13. public interface IUserDao extends IBaseDao<TUser,String>  
  14. {  
  15.     /** 
  16.      * 通过用户名查找用户 
  17.      *  
  18.      * @param   userName    用户名 
  19.      * @return  TUser       用户对象,如果用户名不存在返回null 
  20.      */  
  21.     public  TUser findByUserName(String userName);    
  22. }  


4.具体的Dao实现(Hibernate)
 
Java代码  收藏代码
  1. package com.rc.video.dao.hibernate;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.rc.video.common.base.BaseHibernateDao;  
  6. import com.rc.video.dao.IUserDao;  
  7. import com.rc.video.pojo.TUser;  
  8.   
  9. /** 
  10.  * 用户Dao 
  11.  * @author pasu 
  12.  * @vesion 1.0, 2008-3-2 
  13.  * 
  14.  */  
  15. public class UserHibernateDao extends BaseHibernateDao<TUser,String> implements IUserDao  
  16. {  
  17.     // property constants  
  18.     public static final String USER_NAME = "userName";  
  19.       
  20.     /** 
  21.      * 通过名称查找用户 
  22.      * @return TUser  
  23.      */  
  24.     public TUser findByUserName(String userName)  
  25.     {  
  26.         List<TUser> userList = super.findByProperty(USER_NAME, userName);  
  27.         if(userList.size() != 0)  
  28.         {  
  29.             return userList.get(0);  
  30.         }  
  31.         else  
  32.         {  
  33.             return null;  
  34.         }  
  35.     }  
  36. }  
原创粉丝点击