一个范型的Dao通用类

        首先说明,这个东西最开始是我从网上找到的,但是不记得在那里找到的了。只是觉得非常有用,所以就根据我的需要做了修改,放在了这里,当作一个备忘录吧。

        这个是接口:

java 代码
  1. /**  
  2.  * @author Fred  
  3.  * Jun 25, 2007 5:52:47 PM  
  4.  */  
  5. public interface BaseDao\<T\><t></t><t></t> {   
  6.   
  7.     /**  
  8.      * 根据对象ID来查询对象。  
  9.      * @param id 对象ID。  
  10.      * @return 如果找到对应的对象,则返回该对象。如果不能找到,则返回null。  
  11.      */  
  12.     public T findById(Long id);      
  13.      
  14.     /**  
  15.      * 查询所有的指定对象。  
  16.      */       
  17.     public List<t></t><t></t> listAll();      
  18.        
  19.     /**  
  20.      * 查询,并指定起始的纪录和最大的查询结果集大小以及需要排序的属性和排序的方向。  
  21.      * @param startPos 起始纪录的序号。  
  22.      * @param amount 最大的查询结果集大小。  
  23.      * @param conditions 一个以属性名为key,以属性值为value的Map  
  24.      * @param sortableProperty 需要排序的属性。  
  25.      * @param desc 排序的方向。  
  26.      * @return 结果集。  
  27.      */  
  28.     public List<t></t><t></t> listAndSort(int startPos, int amount, Map conditions, String sortableProperty, boolean asc);   
  29.   
  30.     /**  
  31.      * 统计当前的总纪录数.  
  32.      */  
  33.     public Long countTotalAmount();   
  34.        
  35.     /**  
  36.      * 持久化指定的对象。  
  37.      * @param entity 将要持久化的对象。  
  38.      * @return 持久化以后的对象。  
  39.      */  
  40.     public T save(T entity);     
  41.        
  42.     /**  
  43.      * 在数据库中删除指定的对象。该对象必须具有对象ID。  
  44.      * @param entity 将要被删除的对象。  
  45.      */  
  46.     public void delete(T entity);   
  47.        
  48.     /**  
  49.      * 更新给定的对象。  
  50.      * @param entity 含有将要被更新内容的对象。  
  51.      * @return 更新后的对象。  
  52.      */  
  53.     public T update(T entity);   
  54.   
  55.     /**  
  56.      * 获取标志是否被删除的标志字段。如果是直接删除,返回 null  
  57.      */  
  58.     public String getDeleteToken();   
  59. }  

      然后是其实现类:

java 代码
  1.   
  2. /**  
  3.  * 范型化的BaseDao的实现,作为其他实际被Service层调用的Dao实现的基类。  
  4.  * @author Fred  
  5.  * Jun 25, 2007 5:56:38 PM  
  6.  */  
  7. public class BaseDaoImpl<t class="keyword"></t>extends Model> extends HibernateDaoSupport implements BaseDao<t></t><t></t> {   
  8.   
  9.     private Class<t></t> persistentClass;     
  10.        
  11.     protected static final String DEFAULT_INDEIRECTLY_DELETE_TOKEN = "disused";   
  12.        
  13.     /**  
  14.      * @return the persistentClass  
  15.      */  
  16.     public Class<t></t> getPersistentClass() {   
  17.         return this.persistentClass;   
  18.     }   
  19.        
  20.     /**  
  21.      * 默认构造函数,用于获取范型T的带有类型化信息的Class对象  
  22.      */  
  23.     @SuppressWarnings("unchecked")   
  24.     public BaseDaoImpl() {   
  25.         this.persistentClass = (Class<t></t>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];    
  26.     }   
  27.        
  28.     @SuppressWarnings("unchecked")   
  29.     public T findById(Long id) {   
  30.         return (T) this.getHibernateTemplate().get(this.getPersistentClass(), id);   
  31.     }   
  32.   
  33.     public List<t></t><t></t> listAll() {   
  34.         return this.findByCriteria();   
  35.     }   
  36.        
  37.     @Override  
  38.     public List<t></t><t></t> listAndSort(int startPos, int amount, Map conditions, String sortableProperty,   
  39.             boolean asc) {   
  40.         return this.listAndSort(this.getPersistentClass(), startPos, amount, conditions, sortableProperty, asc, false);   
  41.     }   
  42.        
  43.     @Override  
  44.     public Long countTotalAmount() {   
  45.         StringBuilder hql = new StringBuilder()   
  46.         .append("select count(obj.id) from ")   
  47.         .append(BaseDaoImpl.this.getPersistentClass().getSimpleName())   
  48.         .append(" obj ");   
  49.         if (BaseDaoImpl.this.getDeleteToken() != null) {   
  50.             hql.append("where obj.")   
  51.                .append(BaseDaoImpl.this.getDeleteToken())   
  52.                .append(" = false");   
  53.         }   
  54.         final String hqlString = hql.toString();    
  55.         return (Long) this.getHibernateTemplate().execute(new HibernateCallback() {   
  56.             @Override  
  57.             public Object doInHibernate(Session session) throws HibernateException, SQLException {   
  58.                 Query query = session.createQuery(hqlString.toString());   
  59.                 return query.uniqueResult();   
  60.             }   
  61.         });   
  62.     }   
  63.   
  64.     public T save(T entity) {   
  65.         this.getHibernateTemplate().saveOrUpdate(entity);      
  66.         return entity;      
  67.     }   
  68.        
  69.     public T update(T entity) {   
  70.         this.getHibernateTemplate().update(entity);      
  71.         return entity;      
  72.     }   
  73.        
  74.     public void delete(T entity) {   
  75.         this.getHibernateTemplate().delete(entity);     
  76.     }   
  77.   
  78.     @SuppressWarnings("unchecked")      
  79.     protected List<t></t><t></t> findByCriteria(Criterion... criterion) {      
  80.         DetachedCriteria detachedCrit = DetachedCriteria      
  81.                 .forClass(getPersistentClass());      
  82.         for (Criterion c : criterion) {      
  83.             detachedCrit.add(c);      
  84.         }      
  85.         return getHibernateTemplate().findByCriteria(detachedCrit);      
  86.     }    
  87.        
  88.     /**  
  89.      * 查询,并指定起始的纪录和最大的查询结果集大小以及需要排序的属性和排序的方向。  
  90.      * @param clazz 要被查询的对象对应的Class 
  91.      * @param startPos 起始纪录的序号。  
  92.      * @param amount 最大的查询结果集大小。  
  93.      * @param conditions 一个以属性名为key,以属性值为value的Map  
  94.      * @param sortableProperty 需要排序的属性。  
  95.      * @param desc 排序的方向。  
  96.      * @return 结果集。  
  97.      */  
  98.     @SuppressWarnings("unchecked")   
  99.     protected List<t></t><t></t> listAndSort(Class<t></t> clazz, final int startPos, final int amount,    
  100.             final Map conditions, String sortableProperty, boolean asc, boolean getDisused) {   
  101.            
  102.         boolean hasCondition = false;   
  103.            
  104.         StringBuilder hql = new StringBuilder().append("from ").append(clazz.getSimpleName()).append(" obj ");   
  105.            
  106.         //是否查询被删掉的   
  107.         if (this.getDeleteToken() != null) {   
  108.             hasCondition = true;   
  109.             hql.append("where obj.")   
  110.                .append(this.getDeleteToken())   
  111.                .append(" ");   
  112.             if (getDisused) {   
  113.                 hql.append("is true ");   
  114.             } else {   
  115.                 hql.append("is false ");   
  116.             }   
  117.         }   
  118.            
  119.         //设置查询条件   
  120.         boolean needsAnd = false;   
  121.         if (!conditions.isEmpty()) {   
  122.             if (!hasCondition) {   
  123.                 hql.append("where ");   
  124.             } else {   
  125.                 needsAnd = true;   
  126.             }   
  127.         }   
  128.         for (String property : conditions.keySet()) {   
  129.             if (needsAnd) {   
  130.                 hql.append("and ");   
  131.             }   
  132.             hql.append("obj.").append(property).append(" = :").append(property).append(" ");   
  133.         }   
  134.            
  135.         //排序   
  136.         hql.append("order by ").append(" obj.").append(sortableProperty).append(" ");   
  137.         if (asc) {   
  138.             hql.append("asc");   
  139.         } else {   
  140.             hql.append("desc");   
  141.         }   
  142.            
  143.         //分页   
  144.         final String hqlString = hql.toString();   
  145.         return (List<t></t>) this.getHibernateTemplate().execute(new HibernateCallback() {    
  146.             @Override  
  147.             public Object doInHibernate(Session session) throws HibernateException, SQLException {   
  148.                 Query query = session.createQuery(hqlString);   
  149.                 query.setFirstResult(startPos);   
  150.                 query.setMaxResults(amount);   
  151.                    
  152.                 //给查询条件赋值   
  153.                 for (String property : conditions.keySet()) {   
  154.                     query.setParameter(property, conditions.get(property));   
  155.                 }   
  156.                    
  157.                 return query.list();   
  158.             }   
  159.         });   
  160.     }   
  161.        
  162.     @Override  
  163.     public String getDeleteToken() {   
  164.         return null;   
  165.     }   
  166. }  

      最后,你的实际使用的Dao就可以继承这个基本的Dao实现,只需要添加在实际中需要的特定方法就可以了,对在基本的Dao实现中提供的方法可以直接使用,而且不用考虑类型问题。比如:

       我有一个UserDao,是作对用户对象的操作的:

       接口如下:

java 代码
  1. /**  
  2.  * @author Fred  
  3.  * Jun 26, 2007 12:16:47 AM  
  4.  */  
  5. public interface UserDao extends BaseDao<user></user><user></user> {   
  6.        
  7.     /**  
  8.      * 根据用户ID查找用户  
  9.      */  
  10.     public User find(String userId);   
  11. }  

      实现类如下:

java 代码
  1. /**  
  2.  * @author Fred  
  3.  * Jun 26, 2007 12:20:49 AM  
  4.  */  
  5. public class UserDaoImpl extends BaseDaoImpl<user></user><user></user> implements UserDao {   
  6.   
  7.     @SuppressWarnings("unchecked")   
  8.     public User find(final String userId) {   
  9.         return (User) this.getHibernateTemplate().execute(new HibernateCallback() {   
  10.             @Override  
  11.             public Object doInHibernate(Session session)   
  12.                     throws HibernateException, SQLException {   
  13.                 String hql = "from User user where user.userId = :userId";   
  14.                 Query query = session.createQuery(hql);   
  15.                 query.setString("userId", userId);   
  16.                 return query.uniqueResult();   
  17.             }   
  18.         });   
  19.     }   
  20.        
  21.     @Override  
  22.     public String getDeleteToken() {   
  23.         return "expired";   
  24.     }   
  25. }   

 

      我们的这个UserDaoImpl没有提供对

java 代码
  1. public User findById(Long id);     

      这样的方法的实现,但是通过

java 代码
  1. public class UserDaoImpl extends BaseDaoImpl<user></user> implements UserDao {   
  2.     ......   
  3. }  

      这样的继承,我们的UserDaoImpl一样拥有了这样的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值