Hibernate封装通用数据操作基类DAO

  1. package com.zhanggaosong.ssh.commdao;   
  2. import java.io.Serializable;   
  3. import java.sql.SQLException;   
  4. import java.util.List;   
  5. import java.util.Map;   
  6. import java.util.Set;   
  7. import org.apache.log4j.Logger;   
  8. import org.hibernate.Criteria;   
  9. import org.hibernate.HibernateException;   
  10. import org.hibernate.Query;   
  11. import org.hibernate.Session;   
  12. import org.hibernate.criterion.Expression;   
  13. import org.hibernate.criterion.Order;   
  14. import org.hibernate.type.DateType;   
  15. import org.hibernate.type.FloatType;   
  16. import org.hibernate.type.IntegerType;   
  17. import org.hibernate.type.StringType;   
  18. import org.hibernate.type.Type;   
  19. import org.springframework.orm.hibernate3.HibernateCallback;   
  20. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;   
  21.   
  22. /**  
  23.  * 通用的操作类 dao  
  24.  *   
  25.  * @author 谢晋  
  26.  *   
  27.  */  
  28. public class CommDao<T> extends HibernateDaoSupport {   
  29.     // logger日志对象   
  30.     protected Logger log = Logger.getLogger(this.getClass());   
  31.   
  32.     public CommDao() {   
  33.   
  34.     }   
  35.   
  36.     /**  
  37.      * 添加一个对象  
  38.      */  
  39.     public T addObject(T obj) {   
  40.         this.getHibernateTemplate().save(obj);   
  41.         return obj;   
  42.     }   
  43.   
  44.     /**  
  45.      * 删除一个对象  
  46.      */  
  47.     public T deleteObject(T obj) {   
  48.         this.getHibernateTemplate().delete(obj);   
  49.         return obj;   
  50.     }   
  51.   
  52.     /**  
  53.      * 更新一个对象  
  54.      */  
  55.     public T updateObject(T obj) {   
  56.         this.getHibernateTemplate().update(obj);   
  57.         return obj;   
  58.     }   
  59.   
  60.     /**  
  61.      * 排序+分页功能+条件查询  
  62.      *   
  63.      * @param <E>  
  64.      * @param cl  
  65.      * @param map  
  66.      *            条件参数  
  67.      * @param orderstr  
  68.      *            排序字段 如果为null不排序  
  69.      * @param beginpos  
  70.      *            分页起点 如果为null不分页  
  71.      * @param count  
  72.      *            每页的记录总数 如果为null不分页  
  73.      * @return 返回List集合  
  74.      */  
  75.     public <E> List<E> getOrderObjects(final Class cl, final Map map,   
  76.             final String orderstr, final Integer beginpos, final Integer count) {   
  77.         List<E> list = this.getHibernateTemplate().executeFind(   
  78.                 new HibernateCallback() {   
  79.                     public Object doInHibernate(Session session)   
  80.                             throws HibernateException, SQLException {   
  81.                         Criteria cri = session.createCriteria(cl);   
  82.                         if (map != null) {   
  83.                             Set keyset = map.keySet();   
  84.                             for (Object key : keyset) {   
  85.                                 if (key == null || map.get(key) == null) {   
  86.                                     continue;   
  87.                                 }   
  88.                                 // 如果对应的值是字符串类型,我就是用like匹配   
  89.                                 if (map.get(key).getClass() == String.class) {   
  90.                                     cri.add(Expression.like(key.toString(), map   
  91.                                             .get(key)));   
  92.                                 } else {   
  93.                                     cri.add(Expression.eq(key.toString(), map   
  94.                                             .get(key)));   
  95.                                 }   
  96.                             }   
  97.                         }   
  98.                         if (orderstr != null) {   
  99.                             cri.addOrder(Order.desc(orderstr));   
  100.                         }   
  101.                         if (beginpos != null) {   
  102.                             cri.setFirstResult(beginpos);   
  103.                         } else {   
  104.                             cri.setFirstResult(0);   
  105.                         }   
  106.                         if (count != null) {   
  107.                             cri.setMaxResults(count);   
  108.                         }   
  109.                         return (List<E>) cri.list();   
  110.                     }   
  111.                 });   
  112.         return list;   
  113.     }   
  114.   
  115.     /**  
  116.      * 分页查询 ,传一个hql语句. 和一个参数数组.  
  117.      *   
  118.      * @param hql  
  119.      *            hql语句  
  120.      * @param bindValue  
  121.      *            数组参数  
  122.      * @param first  
  123.      *            分页起点  
  124.      * @param count  
  125.      *            每页的记录总数  
  126.      * @return 返回List集合  
  127.      */  
  128.     public List pageQuery(final String hql, final Object[] bindValue,   
  129.             final Integer first, final Integer count) {   
  130.         List list = this.getHibernateTemplate().executeFind(   
  131.                 new HibernateCallback() {   
  132.                     public Object doInHibernate(Session session)   
  133.                             throws HibernateException, SQLException {   
  134.                         Query query = session.createQuery(hql);   
  135.   
  136.                         if (bindValue != null && bindValue.length >= 1) {   
  137.                             Type[] types = typesFactory(bindValue);   
  138.                             query.setParameters(bindValue, types);   
  139.                         }   
  140.                         if (first != null && first.intValue() >= 0) {   
  141.                             query.setFirstResult(first);   
  142.                             if (count != null && count.intValue() >= 0)   
  143.                                 query.setMaxResults(count);   
  144.                         }   
  145.                         List result = query.list();   
  146.                         return result;   
  147.                     }   
  148.                 });   
  149.         return list;   
  150.     }   
  151.   
  152.     /**  
  153.      * 获取对象对应参数的类型  
  154.      *   
  155.      * @param bindValue  
  156.      * @return  
  157.      */  
  158.     private final Type[] typesFactory(Object[] bindValue) {   
  159.         int count = bindValue.length;   
  160.         Type[] types = new Type[count];   
  161.         for (int i = 0; i < count; i++) {   
  162.             if (bindValue[i].getClass().getName().endsWith("String")) {   
  163.                 types[i] = new StringType();   
  164.             } else if (bindValue[i].getClass().getName().endsWith("Integer")) {   
  165.                 types[i] = new IntegerType();   
  166.             } else if (bindValue[i].getClass().getName().endsWith("Float")) {   
  167.                 types[i] = new FloatType();   
  168.             } else if (bindValue[i].getClass().getName().endsWith("Date")) {   
  169.                 types[i] = new DateType();   
  170.             }   
  171.         }   
  172.         return types;   
  173.     }   
  174.   
  175.     /**  
  176.      * 查询某个类的全部对象  
  177.      *   
  178.      * @param <E>  
  179.      * @param c  
  180.      *            查询类的class  
  181.      * @return  
  182.      */  
  183.     public <E> List<E> selectAllObject(final Class c) {   
  184.         List<E> list = this.getHibernateTemplate().executeFind(   
  185.                 new HibernateCallback() {   
  186.                     public Object doInHibernate(Session session)   
  187.                             throws HibernateException, SQLException {   
  188.                         Criteria cri = session.createCriteria(c);   
  189.                         List<E> list = cri.list();   
  190.                         return list;   
  191.                     }   
  192.                 });   
  193.         return list;   
  194.     }   
  195.   
  196.     /**  
  197.      * 根据 主键 查询某个对象  
  198.      *   
  199.      * @param <E>  
  200.      * @param c  
  201.      * @param id  
  202.      * @return  
  203.      */  
  204.     public <E> E selectObjectById(final Class c, final Serializable id) {   
  205.         E e = (E) this.getHibernateTemplate().execute(new HibernateCallback() {   
  206.             public Object doInHibernate(Session session)   
  207.                     throws HibernateException, SQLException {   
  208.                 E aa = (E) session.get(c, id);   
  209.                 return aa;   
  210.             }   
  211.         });   
  212.         return e;   
  213.     }   
  214.   
  215.     /**  
  216.      * 根据条件,查询一个对象.  
  217.      *   
  218.      * @param <E>  
  219.      * @param c  
  220.      * @param map  
  221.      *            map放条件查询参数 调用的时候?: String username="xiejin" ;  
  222.      *            map.put("username",username);  
  223.      * @return  
  224.      */  
  225.     public <E> E selectUniqueObject(final Class c, final Map map) {   
  226.         E e = (E) this.getHibernateTemplate().execute(new HibernateCallback() {   
  227.             public Object doInHibernate(Session session)   
  228.                     throws HibernateException, SQLException {   
  229.                 Criteria cri = session.createCriteria(c);   
  230.                 cri.add(Expression.allEq(map));   
  231.                 return (E) cri.uniqueResult();   
  232.             }   
  233.         });   
  234.         return e;   
  235.     }   
  236.   
  237.     /**  
  238.      * 带条件的查询.返回list集合  
  239.      *   
  240.      * @param <E>  
  241.      * @param c  
  242.      * @param map  
  243.      *            根据map里面放置的参数  
  244.      * @return 返回一个list对象集合  
  245.      */  
  246.     public <E> List<E> seletcObjectByMap(final Class c, final Map map) {   
  247.         List<E> list = this.getHibernateTemplate().executeFind(   
  248.                 new HibernateCallback() {   
  249.                     public Object doInHibernate(Session session)   
  250.                             throws HibernateException, SQLException {   
  251.                         Criteria cri = session.createCriteria(c);   
  252.                         cri.add(Expression.allEq(map));   
  253.                         List<E> e = cri.list();   
  254.                         return e;   
  255.                     }   
  256.                 });   
  257.         return list;   
  258.     }   
  259.   
  260.     /**  
  261.      * 一个泛型方法:支持条件查询,排序,分页查询.  
  262.      *   
  263.      * @param <E>  
  264.      *            类别  
  265.      * @param cl  
  266.      *            需要查询的类  
  267.      * @param map  
  268.      *            map中put("uname","谢晋"); null or map  
  269.      *            模糊查询用("uname","%"+uname+"%")  
  270.      * @param orderStr  
  271.      *            是否需要排序(升序) null or "属性字段"  
  272.      * @param beginIndex  
  273.      *            分页开始位置 null or Integer  
  274.      * @param count  
  275.      *            记录条数 null or Integer  
  276.      * @return  
  277.      */  
  278.     @SuppressWarnings("unchecked")   
  279.     public <E> List<E> selectObjInfoByMapCondtionAndOrderAndPageQuery(   
  280.             final Class cl, final Map map, final String orderStr,   
  281.             final Integer beginIndex, final Integer count) {   
  282.         List e = this.getHibernateTemplate().executeFind(   
  283.                 new HibernateCallback() {   
  284.                     public Object doInHibernate(Session session)   
  285.                             throws HibernateException, SQLException {   
  286.                         // 使用 Criteria查询 代替复杂得hql语句;   
  287.                         Criteria cri = session.createCriteria(cl);   
  288.                         // 对map进行判断   
  289.                         if (map != null) {   
  290.                             Set keyset = map.keySet();   
  291.                             for (Object key : keyset) {   
  292.                                 // 如果为空则继续遍历   
  293.                                 if (key == null || map.get(key) == null) {   
  294.                                     continue;   
  295.                                 }   
  296.                                 // 如果是参数值是字符串则用模糊查询. like 匹配   
  297.                                 if (map.get(key).getClass() == String.class) {   
  298.                                     cri.add(Expression.like(key.toString(), map   
  299.                                             .get(key)));   
  300.                                 } else {   
  301.                                     cri.add(Expression.eq(key.toString(), map   
  302.                                             .get(key)));   
  303.                                 }   
  304.                             }   
  305.                         }   
  306.                         // 对orderStr 进行判断   
  307.                         if (orderStr != null) {   
  308.                             cri.addOrder(Order.asc(orderStr));// 升序   
  309.                         }   
  310.                         // 对分页 进行判断   
  311.                         if (beginIndex != null && beginIndex.intValue() >= 0) {   
  312.                             cri.setFirstResult(beginIndex.intValue());   
  313.                             if (count != null && count.intValue() >= 0) {   
  314.                                 cri.setMaxResults(count.intValue());   
  315.                             }   
  316.                         }   
  317.                         return (List<E>) cri.list();   
  318.                     }   
  319.                 });   
  320.         return e;   
  321.     }   
posted @ 2013-06-25 22:38  zhgs_cq  阅读(2147)  评论(0编辑  收藏  举报