JPA 基础通用 DAO 父类

/*
 * Copyright (c) 2017 西安才多信息技术有限责任公司。
 * 项目名称:dev-admin
 * 文件名称:JpaBaseDaoImpl.java
 * 日期:17-5-31 下午6:39
 * 作者:yangyan
 *
 */
package cn.firegod.common.jpa;

import cn.firegod.common.Page;
import cn.firegod.common.PageList;
import cn.firegod.dev.vo.CurrentUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 功能:JPA dao 基础类,一个jpa的dao类继承此抽象类后,需要实现 setEntityManager 方法,注入数据源
 * 作者: yangyan
 * 时间: 2014/12/17 .
 */
@Repository
public abstract class JpaBaseDaoImpl<T, PK extends Serializable> implements JpaBaseDao<T, PK> {

    private Class<T> entityClass;
    protected EntityManager entityManager;

    /**
     * 需要注意具体的数据源
     *
     * @param entityManager
     */
    protected abstract void setEntityManager(EntityManager entityManager);

    protected JpaBaseDaoImpl() {
        Class c = getClass();
        Type type = c.getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] parameterizedType = ((ParameterizedType) type)
                    .getActualTypeArguments();
            this.entityClass = (Class<T>) parameterizedType[0];
        }
    }

    private String getIdPropertyName() {
        String idProperty = entityManager.getMetamodel().entity(entityClass).getId(entityManager.getMetamodel().entity(entityClass).getIdType().getJavaType()).getName();
        return idProperty;
    }


    @Override
    public T getById(PK id) {
        return entityManager.find(entityClass, id);
    }

    @Override
    public T loadById(PK id) {
        return entityManager.getReference(entityClass, id);
    }

    @Override
    public <T> T getPropertyById(PK id, String propertyName, Class<T> clazz) {
        Object obj = entityManager.createQuery("select " + propertyName + " from " + entityClass.getName() + " where " + getIdPropertyName() + " = :id").setParameter("id", id).getSingleResult();
        return obj == null ? null : (T) obj;
    }

    @Override
    public void save(T model) {
        this.preInsert(model);
        entityManager.persist(model);
    }

    @Override
    public void saveOrUpdate(T model) {
        entityManager.merge(model);
    }

    @Override
    public void delete(T model) {
        entityManager.remove(model);
    }

    @Override
    public void deleteById(PK... id) {
        if (id != null) {
            for (PK pk : id) {
                if (pk != null) {
                    entityManager.remove(entityManager.getReference(entityClass, pk));
                }
            }
        }
    }

    @Override
    public boolean deleteAll() {
        String hql = "delete " + this.entityClass.getName();
        this.execute(hql);
        return true;
    }

    @Override
    public void execute(String hql, List<Object> params) {
        this.execute(hql, params != null ? params.toArray() : null);
    }

    @Override
    public void execute(String hql, Object... params) {

        Query query = entityManager.createQuery(hql);
        for (int i = 0; i < params.length; i++) {
            query.setParameter(i, params);
        }
        query.executeUpdate();
    }

    @Override
    public void incr(PK id, String propertyName) {
        entityManager.createQuery("update " + entityClass.getName() + " set " + propertyName + "=" + propertyName + "+1 where " + getIdPropertyName() + " =:id")
                .setParameter("id", id).executeUpdate();
    }

    @Override
    public void incr(PK id, String propertyName, Integer n) {
        entityManager.createQuery("update " + entityClass.getName() + " set " + propertyName + "=" + propertyName + "+:n where " + getIdPropertyName() + " =:id")
                .setParameter("n", n).setParameter("id", id).executeUpdate();
    }

    @Override
    public void update(T model) {
        this.preUpdate(model);
        entityManager.merge(model);
    }

    @Override
    public void updateProperty(PK id, String propertyName, Object status) {
        entityManager.createQuery("update " + entityClass.getName() + " set " + propertyName + "=:v where " + getIdPropertyName() + " =:id")
                .setParameter("v", status).setParameter("id", id).executeUpdate();
    }

    @Override
    public void updateProperties(PK id, String[] propertyNames, Object[] values) {
        String hql = "update " + entityClass.getName() + " set ";
        for (int i = 0; i < propertyNames.length; i++) {
            hql += propertyNames[i] + "= :v" + i;
            if (i < propertyNames.length) {
                hql += ",";
            }
        }
        hql += " where " + getIdPropertyName() + " =:id";
        Query query = entityManager.createQuery(hql);
        for (int i = 0; i < values.length; i++) {
            query.setParameter("v" + i, values[i]);
        }
        query.setParameter("id", id).executeUpdate();
    }

    private void preInsert(T model) {
        try {
            Method setCreateDate = this.entityClass.getMethod("setCreateDate", Timestamp.class);
            if (setCreateDate != null) {
                setCreateDate.invoke(model, new Timestamp(System.currentTimeMillis()));
            }
            Method setCreateBy = this.entityClass.getMethod("setCreateBy", Integer.class);
            if (setCreateBy != null) {
                setCreateBy.invoke(model, CurrentUser.getCurrentUserId());
            }
        } catch (NoSuchMethodException e) {
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        try {
            Method delFlag = this.entityClass.getMethod("setDelFlag", Boolean.class);
            if (delFlag != null) {
                delFlag.invoke(model, false);
            }
        } catch (NoSuchMethodException e) {
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        this.preUpdate(model);

    }

    private void preUpdate(T model) {
        try {
            Method setUpdateDate = this.entityClass.getMethod("setUpdateDate", Timestamp.class);
            if (setUpdateDate != null) {
                setUpdateDate.invoke(model, new Timestamp(System.currentTimeMillis()));
            }
            Method setUpdateBy = this.entityClass.getMethod("setUpdateBy", Integer.class);
            if (setUpdateBy != null) {
                setUpdateBy.invoke(model, CurrentUser.getCurrentUserId());
            }
        } catch (NoSuchMethodException e) {
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void updateNotNullProperties(T obj) {
        preUpdate(obj);

        String idName = getIdPropertyName();
        Object idValue = null;
        String hql = "update " + entityClass.getName() + " set ";

        List<String> names = new ArrayList<>();
        List<Object> values = new ArrayList<>();
        PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(this.entityClass);
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            try {
                Method readMethod = propertyDescriptor.getReadMethod();
                String name = propertyDescriptor.getName();
                if ("class".equals(name)) {
                    continue;
                }
                Object v = null;
                if (readMethod != null && (v = readMethod.invoke(obj)) != null) {
                    if (name.equals(idName)) {
                        idValue = v;
                        continue;
                    } else {
                        names.add(name);
                        values.add(v);
                    }

                }
            } catch (IllegalAccessException e) {


            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

        for (int i = 0; i < names.size(); i++) {
            hql += names.get(i) + "= :v" + i;
            if (i+1 < names.size()) {
                hql += ",";
            }
        }
        hql += " where " + getIdPropertyName() + " =:id";
        Query query = entityManager.createQuery(hql);
        for (int i = 0; i < values.size(); i++) {
            query.setParameter("v" + i, values.get(i));
        }
        query.setParameter("id", idValue);

        query.executeUpdate();
    }

    @Override
    public List<T> findAll() {
        return entityManager.createQuery("from " + entityClass.getName()).getResultList();
    }

    @Override
    public List<T> findListByProperty(String properName, Object value) {
        return entityManager.createQuery("from " + entityClass.getName() + " where " + properName + "=:v").setParameter("v", value).getResultList();

    }

    @Override
    public <T> List<T> findListByProperty(Class<T> resultClass, String getPropertyName, String propertyName, Object value) {
        return null;
    }

    @Override
    public List<T> findList(String hql, Object... params) {
        return this.findList(this.entityClass, hql, params);
    }

    @Override
    public <T> List<T> findList(Class<T> clazz, String hql, List<Object> params) {
        return findList(clazz, hql, params != null ? params.toArray() : null);
    }

    @Override
    public <T> List<T> findList(Class<T> clazz, String hql, Object... params) {

        Query query = entityManager.createQuery(hql);
        for (int i = 0; i < params.length; i++) {
            query.setParameter(i, params[i]);
        }
        List resultList = query.getResultList();
        return resultList;
    }

    @Override
    public <T> List<T> findListLimit(Class<T> clazz, String hql, int limit, List<Object> params) {

        return findListLimit(clazz, hql, limit, params != null ? params.toArray() : null);
    }

    @Override
    public <T> List<T> findListLimit(Class<T> clazz, String hql, int limit, Object... params) {

        Query query = entityManager.createQuery(hql);
        for (int i = 0; i < params.length; i++) {
            query.setParameter(i, params[i]);
        }
        query.setFirstResult(0);
        query.setMaxResults(limit);

        List resultList = query.getResultList();
        return resultList;
    }

    @Override
    public <T> PageList<T> findPageList(Page page, Class<T> clazz, String hql, Object... params) {
        Query query = entityManager.createQuery(hql);
        if (page instanceof Page.Offset) {
            query.setFirstResult(((Page.Offset) page).getStart()).setMaxResults(
                    ((Page.Offset) page).getLimit());
        } else {
            query.setFirstResult((page.getPage() - 1) * page.getPageSize())
                    .setMaxResults(page.getPageSize());
        }
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                query.setParameter(i, params[i]);
            }
        }
        page.setTotal(this.getTotalCount(hql, params));
        return new PageList(page, query.getResultList());
    }

    @Override
    public <T> PageList<T> findPageList(Page page, Class<T> clazz, String hql, List<Object> params) {
        return findPageList(page, clazz, hql, params.toArray());
    }

    @Override
    public T getUniqueResultByProperty(String propertyName, Object value) {
        return this.getUniqueResult("from " + this.entityClass.getName()
                + " where " + propertyName + "=?", value);
    }

    @Override
    public void deleteResultsByProperty(String propertyName, Object value) {
        Query query = entityManager.createQuery("delete from " + entityClass.getName() + " where " + propertyName + " = ?");
        query.setParameter(0, value);
        query.executeUpdate();
    }

    @Override
    public void deleteResultsByPropertyInValues(String propertyName, Object... value) {
        String s = StringUtils.leftPad("?", value.length * 2 - 1, "?,");
        Query query = entityManager.createQuery("delete from " + entityClass.getName() + " where " + propertyName + " in (" + s + ") ");
        for (int i = 0; i < value.length; i++) {
            query.setParameter(i, value[i]);
        }
        query.executeUpdate();
    }

    @Override
    public T getUniqueResult(String hql, Object... params) {
        return getUniqueResult(this.entityClass, hql, params);
    }

    @Override
    public <T> T getUniqueResult(Class<T> clazz, String hql, List<Object> params) {
        Query q = entityManager.createQuery(hql);
        if (params != null) {
            for (int i = 0; i < params.size(); i++) {
                q.setParameter(i, params.get(i));
            }
        }
        q.setFirstResult(0);
        q.setMaxResults(1);
        List list = q.getResultList();
        if (list == null || list.isEmpty() || list.get(0) == null) {
            return null;
        }
        return (T) list.get(0);
    }

    @Override
    public <T> T getUniqueResult(Class<T> clazz, String hql, Object... params) {
        return this.getUniqueResult(clazz, hql,
                params == null ? null : Arrays.asList(params));
    }

    @Override
    public PageList<T> findByPage(Page page, String hql, List<Object> params) {
        Query q = entityManager.createQuery(hql);
        if (page instanceof Page.Offset) {
            q.setFirstResult(((Page.Offset) page).getStart()).setMaxResults(
                    ((Page.Offset) page).getLimit());
        } else {
            q.setFirstResult((page.getPage() - 1) * page.getPageSize())
                    .setMaxResults(page.getPageSize());
        }

        if (params != null) {
            for (int i = 0; i < params.size(); i++) {
                q.setParameter(i, params.get(i));
            }
        }
        page.setTotal(this.getTotalCount(hql, params));
        return new PageList(page, q.getResultList());
    }


    @Override
    public PageList<T> findByPage(Page page, String hql, Object... params) {
        return this.findByPage(page, hql, params == null ? null : Arrays.asList(params));
    }

    @Override
    public PageList<T> findByPage(Page page) {
        return this.findByPage(page, "from " + this.entityClass.getName(),
                Collections.EMPTY_LIST);
    }

    @Override
    public void flush() {
        entityManager.flush();
    }

    @Override
    public void clear() {
        entityManager.clear();
    }

    @Override
    public void evict(Object o) {
        entityManager.detach(o);
    }

    @Override
    public boolean isExist(String propertyName, Object value) {
        String hql = "select count(*) from " + entityClass.getName()
                + " where " + propertyName + "=?";
        Query q = entityManager.createQuery(hql);
        q.setParameter(0, value);
        return (Long) q.getSingleResult() > 0;
    }

    @Override
    public long getTotalCount() {
        String hql = "select count(*) from " + entityClass.getName();
        return Long.valueOf(entityManager.createQuery(hql).getSingleResult()
                .toString());
    }

    @Override
    public long getTotalCount(String hql, List<Object> params) {
        Query q = entityManager.createQuery(prepareCountHql(hql));
        if (params != null) {
            for (int i = 0; i < params.size(); i++) {
                q.setParameter(i, params.get(i));
            }
        }
        Object singleResult = q.getSingleResult();
        if (singleResult instanceof Object[]) {
            return Long.valueOf(((Object[]) singleResult)[0].toString()).longValue();
        }
        return Long.valueOf(singleResult.toString()).longValue();
    }

    protected String prepareCountHql(String hql) {


        String fromHql = hql;

        fromHql = " from " + StringUtils.substringAfter(fromHql, "from ");

        fromHql = StringUtils.substringBefore(fromHql, "order by");
//取出查询的字段
        String selectWhat = StringUtils.substringBetween(hql, "select", "from");
//        如果是new ClassName (x.x.x)格式的处理
        if (selectWhat != null && selectWhat.contains("new ") && selectWhat.contains("(") && selectWhat.contains(")")) {
            selectWhat = StringUtils.substringBetween(selectWhat, "(", ")");
        }
//        第一列查询总行数
        String countHql = "select count(*)" + (selectWhat == null ? "" : ", " + selectWhat + " ") + fromHql;
        return countHql;

    }

    @Override
    public long getTotalCount(String hql, Object... params) {
        return this.getTotalCount(hql,
                params == null ? null : Arrays.asList(params));
    }

    @Override
    public void beginTransaction() {
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
    }

    @Override
    public void commitTransaction() {
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.commit();
    }

    @Override
    public void rollbackTransaction() {
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.rollback();
    }


}

 

Leave a Comment

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据