dao层的实现类中的配置BaseDao,所有的DaoImpl可以继承此类

[java]   view plain copy print ?
  1. package com.hfxt.dao.impl;  
  2.   
  3. import java.io.Serializable;  
  4. import java.math.BigInteger;  
  5. import java.util.HashMap;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8.   
  9. import org.hibernate.Query;  
  10. import org.hibernate.Session;  
  11. import org.slf4j.Logger;  
  12. import org.slf4j.LoggerFactory;  
  13. import org.springframework.dao.DataAccessException;  
  14. import org.springframework.orm.hibernate3.HibernateCallback;  
  15. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;  
  16. import org.springframework.transaction.annotation.Transactional;  
  17.   
  18. import com.hfxt.common.Pager;  
  19. import com.hfxt.common.Validity;  
  20. import com.hfxt.dao.IBaseDao;  
  21. import com.hfxt.exception.HibernateDaoSupportException;  
  22.   
  23. public class BaseDao<T,PK extends Serializable> extends HibernateDaoSupport implements IBaseDao<T,PK>  {  
  24.       
  25.       
  26.      protected Logger log = LoggerFactory.getLogger(this.getClass());  
  27.           
  28.           
  29.         private boolean isCacheQueries = true;  
  30.   
  31.         public boolean isCacheQueries() {  
  32.             return isCacheQueries;  
  33.         }  
  34.   
  35.         public void setCacheQueries(boolean isCacheQueries) {  
  36.             this.isCacheQueries = isCacheQueries;  
  37.         }  
  38.   
  39.         /** 
  40.          * The <code>add(T entity)</code> method is add object to database. 
  41.          *  
  42.          * @param entity 
  43.          *            if you want to add entity. 
  44.          *  
  45.          * @throws HibernateDaoSupportException 
  46.          *             Throws HibernateDaoSupportException when accessing and 
  47.          *             manipulating database happen exception. 
  48.          */  
  49.         public PK add(T entity) throws HibernateDaoSupportException {  
  50.             if (null == entity) {  
  51.                 throw new HibernateDaoSupportException("Param(#"  
  52.                         + this.getClass().getName() + ") with value null");  
  53.             }  
  54.   
  55.             try {  
  56.                 PK pk = (PK)this.getHibernateTemplate().save(entity);  
  57.                 log.debug("Executing save method is successful!");  
  58.                 return pk;  
  59.             } catch (DataAccessException e) {  
  60.                 log.error("Error saving entity:{}", e);  
  61.                 throw new HibernateDaoSupportException("Error saving (#"  
  62.                         + this.getClass().getName() + "#):" + e);  
  63.             }  
  64.         }  
  65.           
  66.           
  67.         /** 
  68.          * 更新或保存实体 
  69.          * @param entity 
  70.          */  
  71.         public void saveOrUpdateEntity(T entity){  
  72.             this.getHibernateTemplate().saveOrUpdate(entity);  
  73.         }  
  74.   
  75.         /** 
  76.          * The <code>delete(T entity)</code> method is delete object to database. 
  77.          *  
  78.          * @param entity 
  79.          *            if you want to delete entity. 
  80.          *  
  81.          * @throws HibernateDaoSupportException 
  82.          *             Throws HibernateDaoSupportException when accessing and 
  83.          *             manipulating database happen exception. 
  84.          */  
  85.         public void delete(T entity) throws HibernateDaoSupportException {  
  86.             if (null == entity) {  
  87.                 throw new HibernateDaoSupportException("Param(#"  
  88.                         + this.getClass().getName() + ") with value null");  
  89.             }  
  90.   
  91.             try {  
  92.                 this.getHibernateTemplate().delete(entity);  
  93.                 log.debug("Execute delete method is successful!");  
  94.             } catch (DataAccessException e) {  
  95.                 log.error("Error deleting entity:{}", e);  
  96.                 throw new HibernateDaoSupportException("Error deleting (#"  
  97.                         + this.getClass().getName() + "#):" + e);  
  98.             }  
  99.         }  
  100.   
  101.         /** 
  102.          * The <code>find(T entity)</code> method is find object according object 
  103.          * type. 
  104.          *  
  105.          * @param entity 
  106.          *            if you want to find class condition. 
  107.          * @return List<T> according entity to find object's connection. 
  108.          * @throws HibernateDaoSupportException 
  109.          *             Throws HibernateDaoSupportException when accessing and 
  110.          *             manipulating database happen exception. 
  111.          *  
  112.          */  
  113.         @SuppressWarnings("unchecked")  
  114.         public List<T> find(T entity) throws HibernateDaoSupportException {  
  115.             if (null == entity) {  
  116.                 throw new HibernateDaoSupportException("Param(#"  
  117.                         + this.getClass().getName() + ") with value null");  
  118.             }  
  119.   
  120.             List lists = null;  
  121.             try {  
  122.                 if (isCacheQueries) {  
  123.                     this.getHibernateTemplate().setCacheQueries(true);  
  124.                 } else {  
  125.                     isCacheQueries = true;  
  126.                     this.getHibernateTemplate().setCacheQueries(false);  
  127.                 }  
  128.                 lists = (List<T>) this.getHibernateTemplate().findByExample(entity);  
  129.                 log.debug("Execute find method is successful!");  
  130.             } catch (DataAccessException e) {  
  131.                 log.error("Error finding entity: {}", e);  
  132.                 throw new HibernateDaoSupportException("Error finding (#"  
  133.                         + this.getClass().getName() + "#):" + e);  
  134.             }  
  135.   
  136.             return lists;  
  137.         }  
  138.   
  139.         /** 
  140.          * find object's collection with class 
  141.          *  
  142.          * @param clazz 
  143.          *            according class 
  144.          * @return Object's connection 
  145.          * @throws HibernateDaoSupportException 
  146.          *             when accessing and manipulating database happen exception 
  147.          */  
  148.         @SuppressWarnings("unchecked")  
  149.         public List<T> find(Class<T> clazz) throws HibernateDaoSupportException {  
  150.             if (null == clazz) {  
  151.                 throw new HibernateDaoSupportException(  
  152.                         "Param(#clazz) with value null");  
  153.             }  
  154.             String hql = "FROM " + clazz.getName();  
  155.   
  156.             List<T> lists = null;  
  157.             try {  
  158.                 if (isCacheQueries) {  
  159.                     this.getHibernateTemplate().setCacheQueries(true);  
  160.                 } else {  
  161.                     isCacheQueries = true;  
  162.                     this.getHibernateTemplate().setCacheQueries(false);  
  163.                 }  
  164.                 lists = (List<T>) this.getHibernateTemplate().find(hql);  
  165.                 log.debug("Execute find method is successful!");  
  166.             } catch (DataAccessException e) {  
  167.                 log.error("Error finding entity:{}", e);  
  168.                 throw new HibernateDaoSupportException("Error finding (#"  
  169.                         + this.getClass().getName() + "#):" + e);  
  170.             }  
  171.             return lists;  
  172.         }  
  173.   
  174.         /** 
  175.          * The <code>findById(PK id)</code> method is find object according 
  176.          * primary key. 
  177.          *  
  178.          * @param id 
  179.          *            if you want to find object's primary key 
  180.          * @return T insject object 
  181.          * @throws HibernateDaoSupportException 
  182.          *             Throws HibernateDaoSupportException when accessing and 
  183.          *             manipulating database happen exception. 
  184.          */  
  185.         @SuppressWarnings("unchecked")  
  186.         public T findById(PK id, Class<T> clazz)  
  187.                 throws HibernateDaoSupportException {  
  188.             if (null == id) {  
  189.                 throw new HibernateDaoSupportException("PK with value null");  
  190.             }  
  191.   
  192.             T entity = null;  
  193.             String hql = "FROM " + clazz.getName() + " n where n.id = ";  
  194.               
  195.             if(id instanceof String){  
  196.                 hql +=  "'"+id+"'";  
  197.             }else{  
  198.                 hql += id;  
  199.             }  
  200.             try {  
  201.                 //use 2 leave cache  
  202.                 entity = (T) this.getUniqueBeanResult(hql);  
  203.                 log.debug("Execute findById method is successful!");  
  204.             } catch (DataAccessException e) {  
  205.                 log.error("Error finding entity:{}", e);  
  206.                 throw new HibernateDaoSupportException("Error finding ("  
  207.                         + this.getClass().getName() + "):" + e);  
  208.             }  
  209.             return entity;  
  210.   
  211.         }  
  212.   
  213.         /** 
  214.          * The <code>queryList(PK startRecord, PK pageSize)</code> method is query 
  215.          * objects according startRecord and pagesize're number, object type is 
  216.          * according your implements this method's define type, and implements this 
  217.          * interface abstract class must be override all method and inject entity 
  218.          * type. 
  219.          *  
  220.          * @param startRecord 
  221.          *            Where from the beginning to show this record 
  222.          * @param pageSize 
  223.          *            The number of records per page 
  224.          * @param clazz 
  225.          *            according class 
  226.          * @return List<T> T is your inject object's type, List is query all object 
  227.          *         connection 
  228.          *  
  229.          * @throws HibernateDaoSupportException 
  230.          *             Throws HibernateDaoSupportException when accessing and 
  231.          *             manipulating database happen exception. 
  232.          */  
  233.         public List<T> queryList(int startRecord, int pageSize, Class<T> clazz)  
  234.                 throws HibernateDaoSupportException {  
  235.             return queryList(null, startRecord, pageSize, clazz, null);  
  236.         }  
  237.   
  238.         /** 
  239.          * find object's connection with hql class and param map 
  240.          *  
  241.          * @param hql 
  242.          *            according hql if class param is null 
  243.          * @param startRecord 
  244.          *            Where from the beginning to show this record 
  245.          * @param pageSize 
  246.          *            the number of records per page 
  247.          * @param clazz 
  248.          *            according class 
  249.          * @param properties 
  250.          *            according param map 
  251.          * @return Object's connection 
  252.          * @throws HibernateDaoSupportException 
  253.          *             when accessing and manipulating database happen exception 
  254.          */  
  255.         @SuppressWarnings("unchecked")  
  256.         public List<T> queryList(String hql, final int startRecord,  
  257.                 final int pageSize, Class<T> clazz,  
  258.                 final Map<String, Object> properties)  
  259.                 throws HibernateDaoSupportException {  
  260.             if (hql == null && clazz == null) {  
  261.                 throw new HibernateDaoSupportException(  
  262.                         "Param(#hql#) and param(#clazz#) is null");  
  263.             }  
  264.             if (clazz != null) {  
  265.                 hql = "FROM " + clazz.getName();  
  266.             }  
  267.             final String queryHql = hql;  
  268.             try {  
  269.                 return getHibernateTemplate().executeFind(new HibernateCallback() {  
  270.                     public Object doInHibernate(Session session) {  
  271.                         Query query = session.createQuery(queryHql);  
  272.                         if (isCacheQueries) {  
  273.                             query.setCacheable(true);  
  274.                         } else {  
  275.                             isCacheQueries = true;  
  276.                             query.setCacheable(false);  
  277.                         }  
  278.                         if (!Validity.isEmpty(properties)) {  
  279.                             query.setProperties(properties);  
  280.                         }  
  281.                         if (startRecord >= 0 && pageSize >= 0) {  
  282.                             query.setFirstResult(startRecord).setMaxResults(  
  283.                                     pageSize);  
  284.                         }  
  285.                         return query.list();  
  286.                     }  
  287.                 });  
  288.             } catch (DataAccessException e) {  
  289.                 log.error("Error executing queryList ({}):{}", hql, e);  
  290.                 throw new HibernateDaoSupportException(  
  291.                         "Error executing queryList (" + hql + "):" + e);  
  292.             }  
  293.         }  
  294.   
  295.         /** 
  296.          * The <code>getRecordCount()</code> method is used for getting the total 
  297.          * count of records. 
  298.          *  
  299.          * @return PK return total of record counts 
  300.          * @throws HibernateDaoSupportException 
  301.          *             Throws HibernateDaoSupportException when accessing and 
  302.          *             manipulating database happen exception. 
  303.          */  
  304.         public long getRecordCount(Class<T> clazz)  
  305.                 throws HibernateDaoSupportException {  
  306.             String hql = "SELECT COUNT(*) FROM " + clazz.getName();  
  307.             Integer count = null;  
  308.   
  309.             try {  
  310.                 if (isCacheQueries) {  
  311.                     this.getHibernateTemplate().setCacheQueries(true);  
  312.                 } else {  
  313.                     isCacheQueries = true;  
  314.                     this.getHibernateTemplate().setCacheQueries(false);  
  315.                 }  
  316.                 count = ((Long) this.getHibernateTemplate().find(hql).iterator()  
  317.                         .next()).intValue();  
  318.                 log.debug("Execute getRecordCount method is successful!");  
  319.             } catch (DataAccessException e) {  
  320.                 log.error("Error getting count:{}", e);  
  321.                 throw new HibernateDaoSupportException("Error getting count for ("  
  322.                         + this.getClass().getName() + "):" + e);  
  323.             }  
  324.   
  325.             return count;  
  326.         }  
  327.   
  328.         /** 
  329.          * get count with select hql and param map 
  330.          *  
  331.          * @param selectHql 
  332.          *            according select hql 
  333.          * @param properties 
  334.          *            according param map 
  335.          * @return count of hql 
  336.          * @throws HibernateDaoSupportException 
  337.          *             when accessing and manipulating database happen exception 
  338.          */  
  339.         public int getRecordCount(String selectHql, Map<String, Object> properties)  
  340.                 throws HibernateDaoSupportException {  
  341.             String countHql = getCountHql(selectHql);  
  342.             return ((Long) getUniqueBeanResult(countHql, properties)).intValue();  
  343.         }  
  344.   
  345.         /** 
  346.          * The <code>modifty(T entity)</code> method is update object to database. 
  347.          *  
  348.          * @param entity 
  349.          *            if you want to update entity. 
  350.          * @throws HibernateDaoSupportException 
  351.          *             Throws HibernateDaoSupportException when accessing and 
  352.          *             manipulating database happen exception. 
  353.          */  
  354.         public void modify(T entity) throws HibernateDaoSupportException {  
  355.             if (null == entity) {  
  356.                 throw new HibernateDaoSupportException("Param(#"  
  357.                         + this.getClass().getName() + ") with value null");  
  358.             }  
  359.             try {  
  360.                 this.getHibernateTemplate().update(entity);  
  361.                 log.debug("Execute update method is successful!");  
  362.             } catch (DataAccessException e) {  
  363.                 log.error("Error updating entity:{}", e);  
  364.                 throw new HibernateDaoSupportException("Error updating (#"  
  365.                         + this.getClass().getName() + "#):" + e);  
  366.             }  
  367.         }  
  368.   
  369.         /** 
  370.          * find page object's connection with class 
  371.          *  
  372.          * @param clazz 
  373.          *            according class 
  374.          * @param currentPage 
  375.          *            current page 
  376.          * @param pageSize 
  377.          *            the number of records per page 
  378.          * @return Object's connection 
  379.          * @throws HibernateDaoSupportException 
  380.          *             when accessing and manipulating database happen exception 
  381.          */  
  382.         public Pager<T> findPager(int currentPage, int pageSize, Class<T> clazz)  
  383.                 throws HibernateDaoSupportException {  
  384.             return findPager(null, currentPage, pageSize, clazz, null);  
  385.         }  
  386.   
  387.         /** 
  388.          * find page object's connection with hql and param map 
  389.          *  
  390.          * @param hql 
  391.          *            according hql if class param is null 
  392.          * @param currentPage 
  393.          *            current page 
  394.          * @param pageSize 
  395.          *            the number of records per page 
  396.          * @param properties 
  397.          *            according param map 
  398.          * @return Object's connection 
  399.          * @throws HibernateDaoSupportException 
  400.          *             when accessing and manipulating database happen exception 
  401.          */  
  402.         public Pager<T> findPager(String hql, int currentPage, int pageSize,  
  403.                 Map<String, Object> properties) throws HibernateDaoSupportException {  
  404.             return findPager(hql, currentPage, pageSize, null, properties);  
  405.         }  
  406.   
  407.         /** 
  408.          * find page object's connection with sql and param map 
  409.          *  
  410.          * @param sql 
  411.          *            according sql if class param is null 
  412.          * @param currentPage 
  413.          *            current page 
  414.          * @param pageSize 
  415.          *            the number of records per page 
  416.          * @param properties 
  417.          *            according param map 
  418.          * @return Object's connection 
  419.          * @throws HibernateDaoSupportException 
  420.          *             when accessing and manipulating database happen exception 
  421.          */  
  422.         @SuppressWarnings("unchecked")  
  423.         public Pager findPagerBySql(String sql, int currentPage,  
  424.                 int pageSize, Map<String, Object> properties)  
  425.                 throws HibernateDaoSupportException {  
  426.             log.debug("sql:{},currentPage:{},pageSize:{},propertie:{}",  
  427.                     new Object[] { sql, currentPage, pageSize, properties });  
  428.   
  429.             if (currentPage <= 0) {  
  430.                 throw new HibernateDaoSupportException(  
  431.                         "Param(#currentPage#) value : { " + currentPage + " }");  
  432.             }  
  433.             int totalRecords = 0;  
  434.             String countSql = getCountHql(sql);  
  435.             this.getUniqueBeanResultSql(countSql, properties);  
  436.             totalRecords = ((BigInteger) this.getUniqueBeanResultSql(countSql,  
  437.                     properties)).intValue();  
  438.             Pager page = new Pager();  
  439.             List list = null;  
  440.             page.setTotal(totalRecords);  
  441.             page.setPageSize(pageSize);  
  442.             page.setCurrentPage(currentPage);  
  443.             list = this.queryListSql(sql, (currentPage - 1) * pageSize, pageSize,  
  444.                     properties);  
  445.             page.setPageRecords(list);  
  446.             return page;  
  447.         }  
  448.   
  449.         /** 
  450.          * find object's connection with sql class and param map 
  451.          *  
  452.          * @param sql 
  453.          *            according sql if class param is null 
  454.          * @param startRecord 
  455.          *            Where from the beginning to show this record 
  456.          * @param pageSize 
  457.          *            the number of records per page 
  458.          * @param properties 
  459.          *            according param map 
  460.          * @return Object's connection 
  461.          * @throws HibernateDaoSupportException 
  462.          *             when accessing and manipulating database happen exception 
  463.          */  
  464.         @SuppressWarnings("unchecked")  
  465.         public List queryListSql(final String sql, final int startRecord,  
  466.                 final int pageSize, final Map<String, Object> properties)  
  467.                 throws HibernateDaoSupportException {  
  468.             if (sql == null) {  
  469.                 throw new HibernateDaoSupportException("Param(#sql#) is null");  
  470.             }  
  471.             try {  
  472.                 return getHibernateTemplate().executeFind(new HibernateCallback() {  
  473.                     public Object doInHibernate(Session session) {  
  474.                         Query query = session.createSQLQuery(sql);  
  475.                         if (!Validity.isEmpty(properties)) {  
  476.                             query.setProperties(properties);  
  477.                         }  
  478.                         if (startRecord >= 0 && pageSize >= 0) {  
  479.                             query.setFirstResult(startRecord).setMaxResults(  
  480.                                     pageSize);  
  481.                         }  
  482.                         return query.list();  
  483.                     }  
  484.                 });  
  485.             } catch (DataAccessException e) {  
  486.                 log.error("Error executing queryList ({}):{}", sql, e);  
  487.                 throw new HibernateDaoSupportException(  
  488.                         "Error executing queryList (" + sql + "):" + e);  
  489.             }  
  490.         }  
  491.   
  492.         /** 
  493.          * find page object's connection with hql class and param map 
  494.          *  
  495.          * @param hql 
  496.          *            according hql 
  497.          * @param currentPage 
  498.          *            current page 
  499.          * @param pageSize 
  500.          *            the number of records per page 
  501.          * @param clazz 
  502.          *            according class 
  503.          * @param properties 
  504.          *            according param map 
  505.          * @return Object's connection 
  506.          * @throws HibernateDaoSupportException 
  507.          *             when accessing and manipulating database happen exception 
  508.          */  
  509.         private Pager<T> findPager(String hql, int currentPage, int pageSize,  
  510.                 Class<T> clazz, Map<String, Object> properties)  
  511.                 throws HibernateDaoSupportException {  
  512.             log.debug("hql:{},currentPage:{},pageSize:{},clazz:{},propertie:{}",  
  513.                     new Object[] { hql, currentPage, pageSize, clazz, properties });  
  514.             boolean tempCacheQueries = isCacheQueries;  
  515.             if (currentPage <= 0) {  
  516. //              throw new HibernateDaoSupportException(  
  517. //                      "Param(#currentPage#) value : { " + currentPage + " }");  
  518.                 currentPage = 1;  
  519.             }  
  520.             int totalRecords = 0;  
  521.             if (clazz != null) {  
  522.                 totalRecords = (int)this.getRecordCount(clazz);//TODO long to int?  
  523.             } else {  
  524.                 totalRecords = this.getRecordCount(hql, properties);  
  525.             }  
  526.             if (!tempCacheQueries) {  
  527.                 isCacheQueries = false;  
  528.             }  
  529.             Pager<T> page = new Pager<T>();  
  530.             List<T> list = null;  
  531.             page.setTotal(totalRecords);  
  532.             page.setPageSize(pageSize);  
  533.             list = this.queryList(hql, (currentPage - 1) * pageSize, pageSize,  
  534.                     clazz, properties);  
  535.             //直到找到有数据的页码为止  
  536.             while(list.size() == 0 && currentPage > 1){  
  537.                 currentPage= currentPage -1;  
  538.                 list = this.queryList(hql, (currentPage - 1) * pageSize, pageSize,  
  539.                         clazz, properties);  
  540.             }  
  541.             page.setCurrentPage(currentPage);  
  542.             page.setPageRecords(list);  
  543.             return page;  
  544.         }  
  545.   
  546.         /** 
  547.          * find object's connection with hql 
  548.          *  
  549.          * @param hql 
  550.          *            according hql 
  551.          * @return Object's connection 
  552.          * @throws HibernateDaoSupportException 
  553.          *             when accessing and manipulating database happen exception 
  554.          */  
  555.         public List<T> getObjects(String hql) throws HibernateDaoSupportException {  
  556.             return getObjects(hql, new HashMap<String, Object>(0));  
  557.         }  
  558.   
  559.         /** 
  560.          * find object's connection with hql and param map 
  561.          *  
  562.          * @param hql 
  563.          *            according hql 
  564.          * @param properties 
  565.          *            according param map 
  566.          * @return Object's connection 
  567.          * @throws HibernateDaoSupportException 
  568.          *             when accessing and manipulating database happen exception 
  569.          */  
  570.         @SuppressWarnings("unchecked")  
  571.         public List<T> getObjects(final String hql,  
  572.                 final Map<String, Object> properties)  
  573.                 throws HibernateDaoSupportException {  
  574.             log.debug("hql:{}, properties:{}", hql, properties);  
  575.   
  576.             try {  
  577.                 return getHibernateTemplate().executeFind(new HibernateCallback() {  
  578.                     public Object doInHibernate(Session session) {  
  579.                         Query query = session.createQuery(hql);  
  580.                         if (isCacheQueries) {  
  581.                             query.setCacheable(true);  
  582.                         } else {  
  583.                             isCacheQueries = true;  
  584.                             query.setCacheable(false);  
  585.                         }  
  586.                         if (!Validity.isEmpty(properties)) {  
  587.                             query.setProperties(properties);  
  588.                         }  
  589.                         List<T> list = query.list();  
  590.                         return list;  
  591.                     }  
  592.                 });  
  593.             } catch (DataAccessException e) {  
  594.                 log.error("Error getObjects:{}", e);  
  595.                 throw new HibernateDaoSupportException("Error getObjects (#"  
  596.                         + this.getClass().getName() + "#):" + e);  
  597.             }  
  598.         }  
  599.   
  600.         /** 
  601.          * find object with hql and param map 
  602.          *  
  603.          * @param hql 
  604.          *            according hql 
  605.          * @param properties 
  606.          *            according param map 
  607.          * @return Object which find 
  608.          * @throws HibernateDaoSupportException 
  609.          *             when accessing and manipulating database happen exception 
  610.          */  
  611.         public Object getUniqueBeanResult(final String hql,  
  612.                 final Map<String, Object> properties)  
  613.                 throws HibernateDaoSupportException {  
  614.             log.debug("hql:{}, properties:{}", hql, properties);  
  615.   
  616.             try {  
  617.                 return getHibernateTemplate().execute(new HibernateCallback() {  
  618.                     public Object doInHibernate(Session session) {  
  619.                         Query query = session.createQuery(hql);  
  620.                         if (isCacheQueries) {  
  621.                             query.setCacheable(true);  
  622.                         } else {  
  623.                             isCacheQueries = true;  
  624.                             query.setCacheable(false);  
  625.                         }  
  626.                         if (!Validity.isEmpty(properties)) {  
  627.                             query.setProperties(properties);  
  628.                         }  
  629.                         Object object = query.uniqueResult();  
  630.                         return object;  
  631.                     }  
  632.                 });  
  633.             } catch (DataAccessException e) {  
  634.                 log.error("Error getUniqueBeanResult:{}", e);  
  635.                 throw new HibernateDaoSupportException(  
  636.                         "Error getUniqueBeanResult (#" + this.getClass().getName()  
  637.                                 + "#):" + e);  
  638.             }  
  639.         }  
  640.   
  641.         /** 
  642.          * find object with sql and param map 
  643.          *  
  644.          * @param sql 
  645.          *            according sql 
  646.          * @param properties 
  647.          *            according param map 
  648.          * @return Object which find 
  649.          * @throws HibernateDaoSupportException 
  650.          *             when accessing and manipulating database happen exception 
  651.          */  
  652.         public Object getUniqueBeanResultSql(final String sql,  
  653.                 final Map<String, Object> properties)  
  654.                 throws HibernateDaoSupportException {  
  655.             log.debug("sql:{}, properties:{}", sql, properties);  
  656.             try {  
  657.                 return getHibernateTemplate().execute(new HibernateCallback() {  
  658.                     public Object doInHibernate(Session session) {  
  659.                         Query query = session.createSQLQuery(sql);  
  660.                         if (!Validity.isEmpty(properties)) {  
  661.                             query.setProperties(properties);  
  662.                         }  
  663.                         Object object = query.uniqueResult();  
  664.                         return object;  
  665.                     }  
  666.                 });  
  667.             } catch (DataAccessException e) {  
  668.                 log.error("Error getUniqueBeanResult:{}", e);  
  669.                 throw new HibernateDaoSupportException(  
  670.                         "Error getUniqueBeanResult (#" + this.getClass().getName()  
  671.                                 + "#):" + e);  
  672.             }  
  673.         }  
  674.           
  675.         /** 
  676.          * execute with sql and param arrary 
  677.          *  
  678.          * @param sql 
  679.          *            according sql 
  680.          * @param values 
  681.          *            according param arrary 
  682.          * @return the count of success record 
  683.          * @throws HibernateDaoSupportException 
  684.          *             when accessing and manipulating database happen exception 
  685.          */  
  686.         public int executeSql(final String sql, final Map<String, Object> values)  
  687.                 throws HibernateDaoSupportException {  
  688.             log.debug("hql:{}, params:{}", sql, values);  
  689.             try {  
  690.                 return (Integer) getHibernateTemplate().execute(  
  691.                         new HibernateCallback() {  
  692.                             public Object doInHibernate(Session session) {  
  693.                                 Query query = session.createSQLQuery(sql);  
  694.                                 if (!Validity.isEmpty(values)) {  
  695.                                     query.setProperties(values);  
  696.                                 }  
  697.                                 int i = query.executeUpdate();  
  698.                                 return i;  
  699.                             }  
  700.                         });  
  701.             } catch (DataAccessException e) {  
  702.                 log.error("Error executeUpdate:{}", e);  
  703.                 throw new HibernateDaoSupportException("Error executeUpdate (#"  
  704.                         + this.getClass().getName() + "#):" + e);  
  705.             }  
  706.         }  
  707.   
  708.         /** 
  709.          * find object with hql 
  710.          *  
  711.          * @param hql 
  712.          *            according hql 
  713.          * @return Object which find 
  714.          * @throws HibernateDaoSupportException 
  715.          *             when accessing and manipulating database happen exception 
  716.          */  
  717.         public Object getUniqueBeanResult(String hql)  
  718.                 throws HibernateDaoSupportException {  
  719.             return getUniqueBeanResult(hql, new HashMap<String, Object>(0));  
  720.         }  
  721.   
  722.         /** 
  723.          * update entity with hql and param map 
  724.          *  
  725.          * @param hql 
  726.          *            according hql 
  727.          * @param properties 
  728.          *            according param map 
  729.          * @return the count of success record 
  730.          * @throws HibernateDaoSupportException 
  731.          *             when accessing and manipulating database happen exception 
  732.          */  
  733.         public int executeUpdate(final String hql,  
  734.                 final Map<String, Object> properties)  
  735.                 throws HibernateDaoSupportException {  
  736.             log.debug("hql:{}, properties:{}", hql, properties);  
  737.   
  738.             try {  
  739.                 return (Integer) getHibernateTemplate().execute(  
  740.                         new HibernateCallback() {  
  741.                             public Object doInHibernate(Session session) {  
  742.                                 Query query = session.createQuery(hql);  
  743.                                 if (!Validity.isEmpty(properties)) {  
  744.                                     query.setProperties(properties);  
  745.                                 }  
  746.                                 int i = query.executeUpdate();  
  747.                                 return i;  
  748.                             }  
  749.                         });  
  750.             } catch (DataAccessException e) {  
  751.                 log.error("Error executeUpdate:{}", e);  
  752.                 throw new HibernateDaoSupportException("Error executeUpdate (#"  
  753.                         + this.getClass().getName() + "#):" + e);  
  754.             }  
  755.         }  
  756.   
  757.         /** 
  758.          * update entity with hql and param arrary 
  759.          *  
  760.          * @param hql 
  761.          *            according hql 
  762.          * @param values 
  763.          *            according param arrary 
  764.          * @return the count of success record 
  765.          * @throws HibernateDaoSupportException 
  766.          *             when accessing and manipulating database happen exception 
  767.          */  
  768.         public int executeUpdate(final String hql, final Object[] values)  
  769.                 throws HibernateDaoSupportException {  
  770.             String params = converArrayToString(values);  
  771.             log.debug("hql:{}, params:{}", hql, params);  
  772.   
  773.             try {  
  774.                 return (Integer) getHibernateTemplate().execute(  
  775.                         new HibernateCallback() {  
  776.                             public Object doInHibernate(Session session) {  
  777.                                 Query query = session.createQuery(hql);  
  778.                                 setQueryParam(query, values);  
  779.                                 int i = query.executeUpdate();  
  780.                                 return i;  
  781.                             }  
  782.                         });  
  783.             } catch (DataAccessException e) {  
  784.                 log.error("Error executeUpdate:{}", e);  
  785.                 throw new HibernateDaoSupportException("Error executeUpdate (#"  
  786.                         + this.getClass().getName() + "#):" + e);  
  787.             }  
  788.         }  
  789.   
  790.         /** 
  791.          * group array to string like this (a,b,c) 
  792.          *  
  793.          * @param params 
  794.          *            array param 
  795.          * @return String like this (a,b,c) 
  796.          */  
  797.         protected String groupInParam(String[] params) {  
  798.             StringBuffer inParam = new StringBuffer();  
  799.             inParam.append(" (");  
  800.             for (int i = 0; i < params.length; i++) {  
  801.                 inParam.append(params[i]);  
  802.                 if (i != params.length - 1) {  
  803.                     inParam.append(",");  
  804.                 } else {  
  805.                     inParam.append(") ");  
  806.                 }  
  807.             }  
  808.             return inParam.toString();  
  809.         }  
  810.   
  811.         /** 
  812.          * convert special char 
  813.          *  
  814.          * @param value 
  815.          *            string which need to convert 
  816.          * @return converted string 
  817.          */  
  818.         protected String convertSpecialChar(String value) {  
  819.             String s = null;  
  820.             if (value != null) {  
  821.                 s = value.replace("[""\\\\[").replace("]""\\\\]").replace("%",  
  822.                         "\\\\%").replace("_""\\\\_").replace("^""\\\\^")  
  823.                         .replace("\\", "").replace("'", "");  
  824.             }  
  825.             return s;  
  826.         }  
  827.   
  828.         /** 
  829.          * get count hql with select hql 
  830.          *  
  831.          * @param hql 
  832.          *            select hql 
  833.          * @return count hql 
  834.          */  
  835.         protected String getCountHql(String hql) {  
  836.             if (Validity.isEmpty(hql)) {  
  837.                 log.error("Error getHqlBean because hql is empty");  
  838.                 return "";  
  839.             }  
  840.   
  841.             return "select count(*) "  
  842.                     + hql  
  843.                             .substring(hql.indexOf("from"))  
  844.                             .replace("fetch""")  
  845.                             .replaceAll(  
  846.                                     "\\s((?mi)(left|right|inner)?\\s+join)\\s+[^\\s]*Set\\b",  
  847.                                     " ").split("order by")[0];  
  848.         }  
  849.   
  850.         /** 
  851.          * set param in query 
  852.          *  
  853.          * @param query 
  854.          *            db query 
  855.          * @param values 
  856.          *            param value 
  857.          */  
  858.         private void setQueryParam(Query query, Object[] values) {  
  859.             if (values != null) {  
  860.                 for (int i = 0; i < values.length; i++) {  
  861.                     query.setParameter(i, values[i]);  
  862.                 }  
  863.             }  
  864.         }  
  865.   
  866.         /** 
  867.          * conver array to string 
  868.          *  
  869.          * @param values 
  870.          *            array value 
  871.          * @return string value 
  872.          */  
  873.         private String converArrayToString(Object[] values) {  
  874.             if (values == null) {  
  875.                 return "";  
  876.             }  
  877.             StringBuffer formatValues = new StringBuffer();  
  878.             for (Object value : values) {  
  879.                 formatValues.append("{" + value + "}");  
  880.             }  
  881.             return formatValues.toString();  
  882.         }  
  883.   
  884.         /** 
  885.          *  
  886.          */  
  887.         @SuppressWarnings("unchecked")  
  888.         public List<T> queryListByHql( String hql, Class<T> clazz,final Map<String, Object> properties) throws HibernateDaoSupportException{  
  889.             if (hql == null) {  
  890.                 throw new HibernateDaoSupportException(  
  891.                         "Param(#hql#) and param(#clazz#) is null");  
  892.             }  
  893.             if (clazz != null) {  
  894.                 hql = "FROM " + clazz.getName();  
  895.             }  
  896.             final String queryHql = hql;  
  897.             try {  
  898.                 return getHibernateTemplate().executeFind(new HibernateCallback() {  
  899.                     public Object doInHibernate(Session session) {  
  900.                         Query query = session.createQuery(queryHql);  
  901.                         if (isCacheQueries) {  
  902.                             query.setCacheable(true);  
  903.                         } else {  
  904.                             isCacheQueries = true;  
  905.                             query.setCacheable(false);  
  906.                         }  
  907.                         if (!Validity.isEmpty(properties)) {  
  908.                             query.setProperties(properties);  
  909.                         }  
  910.                         return query.list();  
  911.                     }  
  912.                 });  
  913.             } catch (DataAccessException e) {  
  914.                 log.error("Error executing queryListByHql ({}):{}", hql, e);  
  915.                 throw new HibernateDaoSupportException(  
  916.                         "Error executing queryListByHql (" + hql + "):" + e);  
  917.             }  
  918.         }  
  919.   
  920.           /** 
  921.          * 查询 
  922.          * @param hql 
  923.          * @param properties 
  924.          * @return 
  925.          * @throws HibernateDaoSupportException 
  926.          */  
  927.         public List queryListByHql(String hql,final Map<String, Object> properties) throws HibernateDaoSupportException {  
  928.             if (hql == null) {  
  929.                 throw new HibernateDaoSupportException(  
  930.                         "Param(#hql#) and param(#clazz#) is null");  
  931.             }  
  932.             final String queryHql = hql;  
  933.             try {  
  934.                 return getHibernateTemplate().executeFind(new HibernateCallback() {  
  935.                     public Object doInHibernate(Session session) {  
  936.                         Query query = session.createQuery(queryHql);  
  937.                         if (isCacheQueries) {  
  938.                             query.setCacheable(true);  
  939.                         } else {  
  940.                             isCacheQueries = true;  
  941.                             query.setCacheable(false);  
  942.                         }  
  943.                         if (!Validity.isEmpty(properties)) {  
  944.                             query.setProperties(properties);  
  945.                         }  
  946.                         return query.list();  
  947.                     }  
  948.                 });  
  949.             } catch (DataAccessException e) {  
  950.                 log.error("Error executing queryListByHql ({}):{}", hql, e);  
  951.                 throw new HibernateDaoSupportException(  
  952.                         "Error executing queryListByHql (" + hql + "):" + e);  
  953.             }  
  954.               
  955.         }  
  956.        

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值