[Java] 工具类(增删改查) →→→→→进入此内容的聊天室

来自 , 2019-05-30, 写在 Java, 查看 114 次.
URL http://www.code666.cn/view/53adaf49
  1. import java.io.Serializable;
  2. import java.sql.SQLException;
  3. import java.util.Collection;
  4. import java.util.Iterator;
  5. import java.util.List;
  6. import java.util.Map;
  7.  
  8. import org.apache.commons.lang.StringUtils;
  9. import org.hibernate.Criteria;
  10. import org.hibernate.HibernateException;
  11. import org.hibernate.LockMode;
  12. import org.hibernate.Query;
  13. import org.hibernate.SQLQuery;
  14. import org.hibernate.Session;
  15. import org.hibernate.SessionFactory;
  16. import org.hibernate.criterion.DetachedCriteria;
  17. import org.hibernate.criterion.Restrictions;
  18. import org.hibernate.persister.entity.AbstractEntityPersister;
  19. import org.hibernate.transform.Transformers;
  20. import org.springframework.beans.factory.annotation.Autowired;
  21. import org.springframework.orm.hibernate3.HibernateCallback;
  22. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
  23. import org.springframework.stereotype.Repository;
  24.  
  25. import com.eshore.edms.common.util.EntityUtil;
  26. import com.eshore.edms.common.util.StringHelper;
  27. import com.googlecode.ehcache.annotations.Cacheable;
  28.  
  29. /**
  30.  * 通用数据访问对象.
  31.  */
  32. @SuppressWarnings("unchecked")
  33. public class CommonDAO extends HibernateDaoSupport {
  34.  
  35.     /**
  36.      * 取当前管理的数据访问会话.
  37.      *
  38.      * @return hibernate会话对象
  39.      */
  40.     public Session currentSession() {
  41.         return this.getSession();
  42.     }
  43.    
  44.     /**
  45.      * 装载实体
  46.      *
  47.      * @param pClass
  48.      *            实体类
  49.      * @param primaryKey
  50.      *            实体主键
  51.      */
  52.    
  53.     public <T>T findById(Class<T> pClass, Serializable primaryKey) {
  54.         return this.getHibernateTemplate().get(pClass, primaryKey);
  55.     }
  56.    
  57.     /**
  58.      * 根据指定参数查找
  59.      * @param <T>
  60.      * @param cls
  61.      * @param name
  62.      * @param value
  63.      * @return
  64.      */
  65.     public <T> List<T> findAllByProperty(Class<T> cls, String name, Object value) {
  66.         List<T> lst=this.getHibernateTemplate().find(" from "+cls.getSimpleName()+" where "+name+"=?",new Object[]{value});
  67.         return lst;
  68.     }
  69.    
  70.     /**
  71.      * 根据指定参数查找
  72.      * @param cls
  73.      * @param name
  74.      * @param value
  75.      * @return
  76.      */
  77.         public <T> T findByProperty(Class<T> cls, String name, Object value) {
  78.                 List<?> lst = this.getHibernateTemplate().find(" from " + cls.getSimpleName() + " where " + name + "=?",
  79.                                 new Object[] { value });
  80.                 if (lst != null && !lst.isEmpty()) {
  81.                         return (T) lst.get(0);
  82.                 } else {
  83.                         return null;
  84.                 }
  85.         }
  86.    
  87.     /**
  88.      * 根据指定参数查找
  89.      * @param cls
  90.      * @param name
  91.      * @param value
  92.      * @return
  93.      */
  94.         public <T> List<T> findByProperty(Class<T> cls, Map<String, Object> param) {
  95.                 DetachedCriteria detachedCriteria = DetachedCriteria.forClass(cls, "entity");
  96.                 Criteria criteria = detachedCriteria.getExecutableCriteria(this.getSession());
  97.                 for (Iterator<String> it = param.keySet().iterator(); it.hasNext();) {
  98.                         String key = (String) it.next();
  99.                         Object value = param.get(key);
  100.                         if (value instanceof Collection) {
  101.                                 criteria.add(Restrictions.in(key, (Collection<?>) value));
  102.                         } else if (value instanceof Object[]) {
  103.                                 criteria.add(Restrictions.in(key, (Object[]) value));
  104.                         } else {
  105.                                 criteria.add(Restrictions.eq(key, value));
  106.                         }
  107.                 }
  108.                 return criteria.list();
  109.         }
  110.    
  111.     /**
  112.      * 保存实体.
  113.      *
  114.      * @param pObject
  115.      *            实体对象
  116.      * @return 实体主键
  117.      */
  118.     public void save(Object pObject) {
  119.         this.getHibernateTemplate().saveOrUpdate(pObject);
  120.     }
  121.    
  122.     /**
  123.      * 保存实体,利用主键自动除空
  124.      * @param pObject
  125.      * @throws IllegalAccessException
  126.      * @throws IllegalArgumentException
  127.      */
  128.         public void saveOrUpdate(Object pObject) {
  129.                 try {
  130.                         //如果主键为空,直接设置为null
  131.                         String primaryKeyValue = EntityUtil.getPrimaryKeyValue(
  132.                                         currentSession(), pObject.getClass(), pObject);
  133.                         if (StringUtils.isBlank(primaryKeyValue)) {
  134.                                 EntityUtil.setPrimaryKeyValue(currentSession(),
  135.                                                 pObject.getClass(), pObject, null);
  136.                         }
  137.                 } catch (Exception e) {
  138.                         e.printStackTrace();
  139.                 }
  140.                 this.getHibernateTemplate().saveOrUpdate(pObject);
  141.         }
  142.    
  143.     /**
  144.      * 批量保存
  145.      * @param entities
  146.      */
  147.     public void saveOrUpdateAll(Collection<?> entities){
  148.         this.getHibernateTemplate().saveOrUpdateAll(entities);
  149.     }
  150.  
  151.     /**
  152.      * 删除实体.
  153.      *
  154.      * @param pObject
  155.      *            实体对象
  156.      */
  157.     public void delete(Object pObject) {
  158.         this.getHibernateTemplate().delete(pObject);
  159.     }
  160.    
  161.     /**
  162.      * 批量删
  163.      * @param entities
  164.      */
  165.     public void deleteAll(Collection<?> entities){
  166.         this.getHibernateTemplate().deleteAll(entities);
  167.     }
  168.  
  169.  
  170.     /**
  171.      * 更新实体.
  172.      *
  173.      * @param pObject
  174.      *            实体对象
  175.      */
  176.     public void update(Object pObject) {
  177.         this.getHibernateTemplate().update(pObject);
  178.     }
  179.  
  180.     /**
  181.      *  比较变化保存
  182.      */
  183.     public Object merge(Object po) {
  184.         return this.getSession().merge(po);
  185.     }  
  186.    
  187.     /**
  188.      * 根据参数名称、参数值查询实体对象
  189.      *
  190.      * @param queryString
  191.      * @param paramNames
  192.      * @param values
  193.      * @return
  194.      */
  195.    
  196.     public <T>List<T> findByNamedParam(String queryString, String paramName,Object value) {
  197.         return this.getHibernateTemplate().findByNamedParam(queryString, paramName, value);
  198.     }
  199.  
  200.     /**
  201.      * 根据参数名称、参数值查询实体对象
  202.      *
  203.      * @param queryString
  204.      * @param paramNames
  205.      * @param values
  206.      * @return
  207.      */
  208.    
  209.     public <T>List<T> findByNamedParam(String queryString, String[] paramNames,
  210.             Object[] values) {
  211.         return this.getHibernateTemplate().findByNamedParam(queryString,
  212.                 paramNames, values);
  213.     }  
  214.    
  215.     /**
  216.      *
  217.      * @param queryString
  218.      * @return
  219.      */
  220.     public <T>List<T> find(String queryString){
  221.         return this.getHibernateTemplate().find(queryString);
  222.     }
  223.      
  224.  
  225.     public <T> List<T> find(String queryString,Object[] values){
  226.         return this.getHibernateTemplate().find(queryString,values);
  227.     }
  228.      
  229.     public <T> List<T> find(String queryString,Object values){
  230.         return this.getHibernateTemplate().find(queryString,values);
  231.     }
  232.    
  233.     public <T> List<T> findByHQL(String queryString, Map<String, Object> map) {
  234.         Query query = currentSession().createQuery(queryString);
  235.         if (map != null) {
  236.             query.setProperties(map);
  237.         }
  238.         return query.list();
  239.     }
  240.  
  241.     public <T> List<T> findBySQL(String queryString, Map<String, Object> map) {
  242.         SQLQuery query = currentSession().createSQLQuery(queryString);
  243.         if (map != null) {
  244.             query.setProperties(map);
  245.         }
  246.         return query.list();
  247.     }
  248.    
  249.     public <T> List<T> findBySQL(String queryString, Map<String, Object> map, Class<T> clazz) {
  250.         SQLQuery query = currentSession().createSQLQuery(queryString);
  251.         if (clazz != null) {
  252.             query.addEntity(clazz);
  253.         }
  254.         else {
  255.             query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
  256.         }
  257.         if (map != null) {
  258.             query.setProperties(map);
  259.         }
  260.         return query.list();
  261.     }
  262.    
  263.     /**
  264.      * 根据hql创建查询对象
  265.      * @param hql
  266.      * @param values 数量量可变的参数,按顺序绑定.
  267.      * @return
  268.      */
  269.     public Query createQuery(String hql, final Object... values) {
  270.         Query query = currentSession().createQuery(hql);
  271.         if(values != null){
  272.             for (int i = 0; i < values.length; i++) {
  273.                 query.setParameter(i, values[i]);
  274.             }
  275.         }
  276.         return query;
  277.     }
  278.    
  279.     /**
  280.      * 根据hql创建查询对象
  281.      * @param hql
  282.      * @param values 命名参数,按名称绑定.
  283.      * @return
  284.      */
  285.     public Query createQuery(String hql, final Map<String, Object> values) {
  286.         Query query = currentSession().createQuery(hql);
  287.         if(values != null){
  288.              query.setProperties(values);
  289.         }
  290.         return query;
  291.     }
  292.    
  293.    
  294.    
  295.     /**
  296.      * 执行HQL进行批量修改/删除操作.
  297.      *
  298.      * @param values 数量可变的参数,按顺序绑定.
  299.      * @return 更新记录数.
  300.      */
  301.     public int batchHQLExecute(final String hql, final Object... values) {
  302.         return createQuery(hql, values).executeUpdate();
  303.     }
  304.    
  305.     /**
  306.      * 执行SQL进行批量修改/删除操作.
  307.      *
  308.      * @param values 数量可变的参数,按顺序绑定.
  309.      * @return 更新记录数.
  310.      */
  311.     public int batchSQLExecute(final String sql, final Object... values) {
  312.         return createSQLQuery(sql, values).executeUpdate();
  313.     }
  314.  
  315.    
  316.     /**
  317.      * 根据sql创建查询对象
  318.      *
  319.      * @param queryString
  320.      * @return
  321.      */
  322.     public SQLQuery createSQLQuery(String queryString, final Object... values) {
  323.         SQLQuery query = currentSession().createSQLQuery(queryString);
  324.         if(values != null){
  325.             for (int i = 0; i < values.length; i++) {
  326.                 query.setParameter(i, values[i]);
  327.             }
  328.         }
  329.         return query;
  330.     }
  331.    
  332.    
  333.     /**
  334.      * 根据sql创建查询对象
  335.      *
  336.      * @param queryString
  337.      * @return
  338.      */
  339.     public SQLQuery createSQLQuery(String queryString, final Map<String, Object> values) {
  340.         SQLQuery query = currentSession().createSQLQuery(queryString);
  341.         if(values != null){
  342.             query.setProperties(values);
  343.        }
  344.         return query;
  345.     }
  346.    
  347.         /**
  348.          * 根据sql创建查询对象,并且返回指定的对象列表
  349.          *
  350.          * @param queryString
  351.          * @return
  352.          */
  353.         public SQLQuery createSQLQuery(String sql, final Map<String, Object> values, Class<?> clz) {
  354.                 SQLQuery query = this.getSession().createSQLQuery(sql);
  355.                 if (values != null) {
  356.                         query.setProperties(values);
  357.                 }
  358.                 if (clz != null) {
  359.                         query.addEntity(clz);
  360.                 } else {
  361.                         query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
  362.                 }
  363.                 return query;
  364.         }
  365.    
  366.  
  367.     /**
  368.      *
  369.      * @作者:庞健
  370.      * @类的说明:更新
  371.      * @MSN:
  372.      * @2012-7-30
  373.      */
  374.     public int updateSQLExecute(String sql,Object object){
  375.         Query query=this.getSession().createSQLQuery(sql);
  376.         if(object!=null){
  377.             query.setProperties(object);
  378.         }
  379.         return query.executeUpdate();
  380.     }
  381.     /**
  382.      * 锁定实体
  383.      *
  384.      * @param entity
  385.      * @param lockMode
  386.      */
  387.     public void refresh(Object entity, LockMode lockMode) {
  388.         this.getHibernateTemplate().refresh(entity, lockMode);
  389.     }
  390.    
  391.     /**
  392.      * 手动提交事务,提交前会自动调用一个flush()函数,会把缓存中的数据全部输出去
  393.      * @author Liangr
  394.      * Jan 28, 2014
  395.      * void
  396.      */
  397.     public void commit() {
  398.         this.getSession().getTransaction().commit();
  399.     }
  400.  
  401.     /**
  402.      * 刷新一级缓存区的内容,使之与数据库数据保持同步
  403.      */
  404.     public void flush() {
  405.         this.getHibernateTemplate().flush();
  406.     }
  407.  
  408.     /**
  409.      * 将一级缓存中的所有持久化对象清除,释放其占用的内存资源
  410.      */
  411.     public void clear() {
  412.         this.getHibernateTemplate().clear();
  413.     }
  414.    
  415.     /**
  416.      * 将对象从二级缓存中删除,持久化对象未清除
  417.      */
  418.     @SuppressWarnings({ "deprecation"})
  419.     public void evict(Class<?> clazz,Serializable poId) {
  420.         this.getSession().getSessionFactory().evict(clazz, poId);
  421.     }
  422.    
  423.     /**
  424.      * 将对象从一级缓存中删除,持久化对象未清除
  425.      */
  426.     public void evict(Object po) {
  427.         this.getSession().evict(po);
  428.     }  
  429.  
  430.    
  431.  
  432.     /**
  433.      *
  434.      * @param sessionFactory
  435.      */
  436.     @Autowired
  437.     public void setSession$Factory(SessionFactory sessionFactory) {
  438.            super.setSessionFactory(sessionFactory);        
  439.     }
  440.    
  441.     public SessionFactory getSession$Factory() {
  442.         return super.getSessionFactory();
  443.     }
  444.    
  445.     /**
  446.      * 调用存储过程
  447.      *
  448.      * @param procedureSql example: "{call pro_ADD_PARTITION_wareid(?,?)}"
  449.      * @param values
  450.      * @return
  451.      */
  452.     public <T>int callProcedure(String procedureSql, final Object... values) {
  453.         SQLQuery query = currentSession().createSQLQuery(procedureSql);
  454.         if(values != null){
  455.             for (int i = 0; i < values.length; i++) {
  456.                 query.setParameter(i, values[i]);
  457.             }
  458.         }
  459.         int executeUpdate = query.executeUpdate();
  460.         return executeUpdate;
  461.     }
  462.    
  463.     /**
  464.      * 根据 序列 名称跟长度获取唯一编码
  465.      * @param sequenceName
  466.      * @param totalLen
  467.      * @return
  468.      */
  469.     public String getSequence(final String sequenceName, int totalLen) {
  470.                 Integer s = (Integer) getHibernateTemplate().execute(
  471.                                 new HibernateCallback<Object>() {
  472.                                         public Object doInHibernate(Session session)
  473.                                                         throws HibernateException, SQLException {
  474.                                                 SQLQuery query = session.createSQLQuery("select "
  475.                                                                 + sequenceName + ".nextval from dual");
  476.                                                 return new Integer(query.list().get(0).toString());
  477.                                         }
  478.                                 });
  479.  
  480.                 return StringHelper.lpad("" + s, totalLen, '0');
  481.         }
  482.    
  483.     @Cacheable(cacheName="system")
  484.         public String getTableName(Class<?> clazz) {
  485.                 AbstractEntityPersister meta = (AbstractEntityPersister) this.getSessionFactory().getClassMetadata(clazz);
  486.                 // 实体名称
  487.                 String entityName = meta.getTableName();
  488.                 return entityName;
  489.         }
  490.    
  491.     public Object execute(HibernateCallback<?> hibernateCallback) {
  492.                 return super.getHibernateTemplate().execute(hibernateCallback);
  493.         }
  494. }
  495.  

回复 "工具类(增删改查)"

这儿你可以回复上面这条便签

captcha