hibernate使用jpa对于基础dao的封装

2017-05-11  本文已影响271人  huangxiongbiao

一、dao的接口

package com.hm.dao;

import java.util.List;
import java.util.Map;

import com.hm.common.util.QueryParameter;

/**
 * 数据操作基类接口
 */
public interface BaseDAO<T, PK extends java.io.Serializable> {
    
    /**
     * 保存对象
     * @param entity    实体
     * @return          1:操作成功 0:操作失败
     */
    public int save(T entity);
    
    /**
     * 更新对象信息
     * @param entity    实体
     * @return          1:操作成功 0:操作失败
     */
    public int update(T entity);
    
    /**
     * 删除对象
     * @param entity    实体
     * @return          >0:操作成功
     */
    public int delete(T entity );
    
    /**
     * 删除对象
     * @param id        主键
     * @return          >0:操作成功
     */
    public int delete(PK id);
    
    /**
     * 根据ID获取实体对象
     * @param id    ID主键
     * @return      实体
     */
    public T findById(PK id);

    /**
     * 根据EJB-QL查询对象
     * @param queryString   QL语句
     * @return              数据集合
     */
    public List<T> findByQL(String queryString);

    /**
     * 根据EJB-QL查询对象
     * @param queryString   QL语句
     * @param map           参数
     * @return              数据集合
     */
    public List<T> findByQL(String queryString, Map<String, Object> map);
    
    /**
     * 根据SQL查询对象
     * @param queryString   SQL语句
     * @return              数据集合
     */
    public List<Object> findBySQL(String queryString);
    
    /**
     * 根据SQL查询对象
     * @param queryString   SQL语句
     * @param map           参数
     * @return              数据集合
     */
    public List<Object> findBySQL(String queryString, Map<String, Object> map);
    
    /**
     * 根据EJB-QL返回对象记录数
     * @param queryString   EJ-QL语句
     * @return              总记录数
     */
    public int getCountByQL(String queryString);

    /**
     * 根据EJB-QL返回对象记录数
     * @param queryString   EJ-QL语句
     * @param map           参数
     * @return              总记录数
     */
    public int getCountByQL(String queryString, Map<String, Object> map);
    
    /**
     * 根据SQL返回对象记录数
     * @param queryString   SQL语句
     * @return              总记录数
     */
    public int getCountBySQL(String queryString);

    /**
     * 根据SQL返回对象记录数
     * @param queryString   SQL语句
     * @param map           参数
     * @return              总记录数
     */
    public int getCountBySQL(String queryString, Map<String, Object> map);

    /**
     * 根据SQL返回对象记录数
     * @param queryString   SQL语句
     * @param map           参数
     * @return              总记录数
     */
    public int getCountBySQL2(String queryString, Map<String, Object> map);
    
    /**
     * 根据EJB-QL查询对象
     * @param queryString   QL语句
     * @param maxSize       最大数量
     * @param firstId       第一条记录
     * @return              数据集合
     */
    public List<T> findByQL(String queryString, int maxSize, int firstId);

    /**
     * 根据EJB-QL查询对象
     * @param queryString   QL语句
     * @param maxSize       最大数量
     * @param firstId       第一条记录
     * @param map           参数
     * @return              数据集合
     */
    public List<T> findByQL(String queryString, int maxSize, int firstId, Map<String, Object> map);
    
    /**
     * 根据SQL查询对象
     * @param queryString   SQL语句
     * @param maxSize       最大数量
     * @param firstId       第一条记录
     * @return              数据集合
     */
    public List<Object> findBySQL(String queryString, int maxSize, int firstId);
    
    /**
     * 根据SQL查询对象
     * @param queryString   SQL语句
     * @param maxSize       最大数量
     * @param firstId       第一条记录
     * @param map           参数
     * @return              数据集合
     */
    public List<Object> findBySQL(String queryString, int maxSize, int firstId, Map<String, Object> map);
    
    /**
     * 执行更新语句
     * @param queryString   EJ-QL语句
     * @return              影响记录数
     */
    public int executeUpdateByQL(String queryString);

    /**
     * 执行更新语句
     * @param queryString   EJ-QL语句
     * @param map           参数
     * @return              影响记录数
     */
    public int executeUpdateByQL(String queryString, Map<String, Object> map);
    
    /**
     * 执行更新语句
     * @param queryString   SQL语句
     * @return              影响记录数
     */
    public int executeUpdateBySQL(String queryString);
    
    /**
     * 执行更新语句
     * @param queryString   SQL语句
     * @param map           参数
     * @return              影响记录数
     */
    public int executeUpdateBySQL(String queryString, Map<String, Object> map);

    /**
     * 执行事务
     * @param queryParameterList    要执行的QL语句集合
     * @return                      操作结果 true | false
     */
    public boolean executeTransactionalByQL(List<QueryParameter> queryParameterList);

    /**
     * 执行事务
     * @param queryParameterList    要执行的SQL语句集合
     * @return                      操作结果 true | false
     */
    public boolean executeTransactionalBySQL(List<QueryParameter> queryParameterList);
    
    /**
     * 根据HQL查询对象
     * @param queryString   SQL语句
     * @param maxSize       最大数量
     * @param firstId       第一条记录
     * @param map           参数
     * @return              数据集合
     */
    public List<Object> findObjectByQL(String queryString, int maxSize, int firstId, Map<String, Object> map);
}

二、dao的实现

package com.hm.dao.jpa;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hm.common.util.QueryParameter;
import com.hm.dao.BaseDAO;

/**
 * 数据操作基类实现类
 */
@SuppressWarnings("unchecked")
public class BaseDAOImpl<T, PK extends java.io.Serializable> implements BaseDAO<T, PK> {
    
    private static Log log;

    private Class<T> entityClass;

    @PersistenceContext
    private EntityManager entityManager;

    // @PersistenceContext
    private EntityManagerFactory entityManagerFactory;
    
    @PersistenceUnit
    public void setEntityManagerFactory(EntityManagerFactory emf) {
        this.entityManagerFactory = emf;
    }

    /**
     * 构造方法
     */
    public BaseDAOImpl(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public Log getLog() {
        if(null == log) {
            log = LogFactory.getLog(this.getClass());
        }
        return log;
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public Class<T> getEntityClass() {
        return entityClass;
    }

    public void setEntityClass(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    @Transactional
    public int save(T entity) {
        try {
            entityManager.persist(entity);
        } catch (Exception e) {
            getLog().error("保存对象发生异常:" +e.getMessage());
            return 0;
        }
        return 1;
    }

    @Transactional
    public int update(T entity) {
        try {
            entity = entityManager.merge(entity);
        } catch (Exception e) {
            getLog().error("获取对象发生异常:"+e.getMessage());
            return 0;
        } 
        return 1;
    }

    @Transactional
    public int delete(T entity) {
        try {
            entityManager.remove(entityManager.merge(entity));
            return 1;
        } catch (Exception e) {
            getLog().error("删除对象发生异常:"+e.getMessage());
            return 0;
        }
    }

    @Transactional
    public int delete(PK id) {
        return this.delete(this.findById(id));
    }

    public T findById(PK id) {
        T entity = null;
        try {
            entity = entityManager.find(entityClass, id);
        } catch (Exception e) {
            getLog().error("获取对象发生异常:"+e.getMessage());
        }
        return entity;
    }

    public List<T> findByQL(String queryString) {
        List<T> rList = new ArrayList<T>();
        try {
            rList = (List<T>)entityManager.createQuery(queryString).getResultList();
        } catch (Exception e) {
            getLog().error("获取对象发生异常:"+e.getMessage());
        } 
        return rList;
    }

    public List<T> findByQL(String queryString, Map<String, Object> map) {
        List<T> rList = new ArrayList<T>();
        try {
            Query q = this.getEntityManager().createQuery(queryString);
            if(null != map) {
                for (String key : map.keySet()) {
                    q.setParameter(key, map.get(key));
                }
            }
            rList = (List<T>)q.getResultList();
        } catch (Exception e) {
            getLog().error("获取对象发生异常:"+e.getMessage());
        } 
        return rList;
    }
    
    public List<Object> findBySQL(String queryString) {
        List<Object> rList = new ArrayList<Object>();
        try {
            Query q = this.getEntityManager().createNativeQuery(queryString);
            rList = q.getResultList();
        } catch (Exception e) {
            this.getLog().error("获取对象发生异常:"+e.getMessage());
        } 
        return rList;
    }
    
    public List<Object> findBySQL(String queryString, Map<String, Object> map) {
        List<Object> rList = new ArrayList<Object>();
        try {
            Query q = this.getEntityManager().createNativeQuery(queryString);
            if(null != map) {
                for (String key : map.keySet()) {
                    q.setParameter(key, map.get(key));
                }
            }
            rList = q.getResultList();
        } catch (Exception e) {
            this.getLog().error("获取对象发生异常:"+e.getMessage());
        } 
        return rList;
    }

    public List<T> findByQL(String queryString, int maxSize, int firstId) {
        List<T> rList = new ArrayList<T>();
        try {
            Query q = this.getEntityManager().createQuery(queryString);
            q.setMaxResults(maxSize);
            q.setFirstResult(firstId);
            rList = q.getResultList();
        } catch (Exception e) {
            this.getLog().error("获取对象发生异常:"+e.getMessage());
        } 
        return rList;
    }

    public List<T> findByQL(String queryString, int maxSize, int firstId, Map<String, Object> map) {
        List<T> rList = new ArrayList<T>();
        try {
            Query q = this.getEntityManager().createQuery(queryString);
            if(null != map) {
                for (String key : map.keySet()) {
                    q.setParameter(key, map.get(key));
                }
            }
            q.setMaxResults(maxSize);
            q.setFirstResult(firstId);
            rList = q.getResultList();
        } catch (Exception e) {
            this.getLog().error("获取对象发生异常:"+e.getMessage());
            e.printStackTrace();
        } 
        return rList;
    }
    
    public List<Object> findObjectByQL(String queryString, int maxSize, int firstId, Map<String, Object> map) {
        List<Object> rList = new ArrayList<Object>();
        try {
            Query q = this.getEntityManager().createQuery(queryString);
            if(null != map) {
                for (String key : map.keySet()) {
                    q.setParameter(key, map.get(key));
                }
            }
            q.setMaxResults(maxSize);
            q.setFirstResult(firstId);
            rList = q.getResultList();
        } catch (Exception e) {
            this.getLog().error("获取对象发生异常:"+e.getMessage());
        } 
        return rList;
    }
    
    public List<Object> findBySQL(String queryString, int maxSize, int firstId) {
        List<Object> rList = new ArrayList<Object>();
        try {
            Query q = this.getEntityManager().createNativeQuery(queryString);
            q.setMaxResults(maxSize);
            q.setFirstResult(firstId);
            rList = q.getResultList();
        } catch (Exception e) {
            this.getLog().error("获取对象发生异常:"+e.getMessage());
        } 
        return rList;
    }
    
    public List<Object> findBySQL(String queryString, int maxSize, int firstId, Map<String, Object> map) {
        List<Object> rList = new ArrayList<Object>();
        try {
            Query q = this.getEntityManager().createQuery(queryString);
            if(null != map) {
                for (String key : map.keySet()) {
                    q.setParameter(key, map.get(key));
                }
            }
            q.setMaxResults(maxSize);
            q.setFirstResult(firstId);
            rList = q.getResultList();
        } catch (Exception e) {
            this.getLog().error("获取对象发生异常:"+e.getMessage());
        } 
        return rList;
    }

    public int getCountByQL(String queryString) {
        int intCount = 0;
        try {
            Query q = this.getEntityManager().createQuery(queryString);
            intCount = ((Long)q.getSingleResult()).intValue();
        } catch (Exception e) {
            getLog().error("获取对象总数发生异常:"+e.getMessage());
            e.printStackTrace();
        } 
        return intCount;
    }

    public int getCountByQL(String queryString, Map<String, Object> map) {
        int intCount = 0;
        try {
            Query q = this.getEntityManager().createQuery(queryString);
            if(null != map) {
                for (String key : map.keySet()) {
                    q.setParameter(key, map.get(key));
                }
            }
            intCount = ((Long)q.getSingleResult()).intValue();
            
        } catch (Exception e) {
            getLog().error("获取对象总数发生异常:"+e.getMessage());
            e.printStackTrace();
        } 
        return intCount;
    }
    
    public int getCountBySQL(String queryString) {
        int intCount = 0;
        try {
            Query q = this.getEntityManager().createNativeQuery(queryString);
            intCount = ((Integer)q.getSingleResult()).intValue();
        } catch (Exception e) {
            getLog().error("获取对象总数发生异常:"+e.getMessage());
            e.printStackTrace();
        } 
        return intCount;
    }
    
    public int getCountBySQL(String queryString, Map<String, Object> map) {
        int intCount = 0;
        try {
            Query q = this.getEntityManager().createNativeQuery(queryString);
            if(null != map) {
                for (String key : map.keySet()) {
                    q.setParameter(key, map.get(key));
                }
            }
            intCount = ((Integer)q.getSingleResult()).intValue();
        } catch (Exception e) {
            getLog().error("获取对象总数发生异常:"+e.getMessage());
            e.printStackTrace();
        } 
        return intCount;
    }

    public int getCountBySQL2(String queryString, Map<String, Object> map) {
        int intCount = 0;
        try {
            Query q = this.getEntityManager().createNativeQuery(queryString);
            if(null != map) {
                for (String key : map.keySet()) {
                    q.setParameter(key, map.get(key));
                }
            }
            String str  = q.getSingleResult().toString();
            intCount = Integer.parseInt(str);
        } catch (Exception e) {
            getLog().error("获取对象总数发生异常:"+e.getMessage());
            e.printStackTrace();
        } 
        return intCount;
    }
    
    @Transactional
    public int executeUpdateByQL(String queryString) {
        int intCount = 0;
        try {
            intCount = this.getEntityManager().createQuery(queryString).executeUpdate();
        } catch (Exception e) {
            getLog().error("执行更新语句发生异常:"+e.getMessage());
            e.printStackTrace();
        } 
        return intCount;
    }

    @Transactional
    public int executeUpdateByQL(String queryString, Map<String, Object> map) {
        int intCount = 0;
        try {
            Query q = this.getEntityManager().createQuery(queryString);
            if(null != map) {
                for (String key : map.keySet()) {
                    q.setParameter(key, map.get(key));
                }
            }
            intCount = q.executeUpdate();
        } catch (Exception e) {
            getLog().error("执行更新语句发生异常:"+e.getMessage());
            e.printStackTrace();
        } 
        return intCount;
    }

    @Transactional
    public int executeUpdateBySQL(String queryString) {
        int intCount = 0;
        try {
            intCount = this.getEntityManager().createNativeQuery(queryString).executeUpdate();
        } catch (Exception e) {
            getLog().error("执行更新语句发生异常:"+e.getMessage());
        } 
        return intCount;
    }

    @Transactional
    public int executeUpdateBySQL(String queryString, Map<String, Object> map) {
        int intCount = 0;
        try {
            Query q = this.getEntityManager().createNativeQuery(queryString);
            if(null != map) {
                for (String key : map.keySet()) {
                    q.setParameter(key, map.get(key));
                }
            }
            intCount = q.executeUpdate();
        } catch (Exception e) {
            getLog().error("执行更新语句发生异常:"+e.getMessage());
            e.printStackTrace();
        } 
        return intCount;
    }

    @Override
    public boolean executeTransactionalByQL(List<QueryParameter> queryParameterList) {
        if(null == queryParameterList || queryParameterList.isEmpty()) {
            return false;
        }
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        try {
            //this.getEntityManager().getTransaction().begin();
            entityManager.getTransaction().begin();
            for(QueryParameter queryParameter : queryParameterList) {
                //Query q = this.getEntityManager().createQuery(queryParameter.getQueryString());
                Query q;
                if(StringUtils.indexOf(queryParameter.getQueryString(), "insert") >= 0 || queryParameter.getType() == "SQL")
                {
                    q = entityManager.createNativeQuery(queryParameter.getQueryString());
                }
                else 
                {
                    q = entityManager.createQuery(queryParameter.getQueryString());
                }
                if(null != queryParameter.getParameterMap()) {
                    for (String key : queryParameter.getParameterMap().keySet()) {
                        q.setParameter(key, queryParameter.getParameterMap().get(key));
                    }
                }
                q.executeUpdate();
            }
            //this.getEntityManager().getTransaction().commit();
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            getLog().error("执行事务发生异常:"+e.getMessage());
            //this.getEntityManager().getTransaction().rollback();
            entityManager.getTransaction().rollback();
            e.printStackTrace();
            return false;
        } finally {
            entityManager.close();
        }
        return true;
    }

    @Override
    public boolean executeTransactionalBySQL(List<QueryParameter> queryParameterList) {
        if(null == queryParameterList || queryParameterList.isEmpty()) {
            return false;
        }
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        try {
            //this.getEntityManager().getTransaction().begin();
            entityManager.getTransaction().begin();
            for(QueryParameter queryParameter : queryParameterList) {
                //Query q = this.getEntityManager().createQuery(queryParameter.getQueryString());
                Query q = entityManager.createNativeQuery(queryParameter.getQueryString());
                if(null != queryParameter.getParameterMap()) {
                    for (String key : queryParameter.getParameterMap().keySet()) {
                        q.setParameter(key, queryParameter.getParameterMap().get(key));
                    }
                }
                q.executeUpdate();
            }
            //this.getEntityManager().getTransaction().commit();
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            getLog().error("执行事务发生异常:"+e.getMessage());
            //this.getEntityManager().getTransaction().rollback();
            entityManager.getTransaction().rollback();
            e.printStackTrace();
            return false;
        } finally {
            entityManager.close();
        }
        return true;
    }
}

上一篇下一篇

猜你喜欢

热点阅读