Progr1mmer 6 年 前
コミット
bfc90c82a6

+ 60 - 53
mysql-starter/src/main/java/com/yihu/mysql/query/BaseJpaService.java

@ -6,11 +6,10 @@ import org.hibernate.Session;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@ -35,30 +34,33 @@ import java.util.*;
 * @created 2016.2.3。
 */
@Transactional(propagation = Propagation.SUPPORTS)
public class BaseJpaService<T, R> {
public abstract class BaseJpaService<T, R extends CrudRepository> {
    private final int defaultPage = 1;
    private final int defaultSize = 30;
    protected final int defaultPage = 1;
    protected final int defaultSize = 15;
    protected Class<T> tClass;
    protected Class<R> repoClass;
    private Class<R> repoClass;
    @PersistenceContext
    protected EntityManager entityManager;
    public BaseJpaService(){
    public BaseJpaService() {
        Type genType = getClass().getGenericSuperclass();
        if ((genType instanceof ParameterizedType)) {
        if (genType instanceof ParameterizedType) {
            Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
            if (params.length==2) {
                repoClass = (Class) params[1];
            if (params.length == 2) {
                tClass = (Class<T>) params[0];
                repoClass = (Class<R>) params[1];
            }
        }
    }
    public T save(T entity) {
    public T save (T entity) {
        return (T) getRepository().save(entity);
    }
    public void batchInsert(List list) {
    public void batchInsert (List list) {
        for (int i = 0; i < list.size(); i++) {
            entityManager.persist(list.get(i));
            if (i % 30 == 0) {
@ -77,32 +79,18 @@ public class BaseJpaService<T, R> {
    }
    public void delete(Iterable ids) {
        Iterable list = getRepository().findAll(ids);
        getRepository().delete(list);
        getRepository().delete(ids);
    }
    public int delete(Object[] ids){
        if (repoClass != null) {
            Type [] types = repoClass.getGenericInterfaces();
            for (Type type : types) {
                if (type.getClass().equals(ParameterizedTypeImpl.class)) {
                    ParameterizedType _type = (ParameterizedType)type;
                    if (_type.getRawType().getTypeName().equals(PagingAndSortingRepository.class.getName())) {
                        Type [] actualTypeArguments = _type.getActualTypeArguments();
                        if (actualTypeArguments.length == 2) {
                            if (actualTypeArguments[1].getTypeName().equals(Integer.class.getName())) {
                                Integer [] _ids = new Integer[ids.length];
                                for (int i = 0; i < ids.length; i ++) {
                                    _ids[i] = new Integer(ids[i].toString());
                                }
                                ids = _ids;
                            }
                        }
                    }
                }
        if (Integer.class.getName().equals(getEntityIdType())) {
            Integer [] _ids = new Integer[ids.length];
            for (int i = 0; i < ids.length; i ++) {
                _ids[i] = new Integer(ids[i].toString());
            }
            ids = _ids;
        }
        String hql = " DELETE FROM " + getEntityClass().getName() + " WHERE " + getEntityIdFiled() + " in(:ids)";
        String hql = "DELETE FROM " + getEntityClass().getName() + " WHERE " + getEntityIdFiled() + " in(:ids)";
        Query query = currentSession().createQuery(hql);
        query.setParameterList("ids", ids);
        return query.executeUpdate();
@ -112,7 +100,7 @@ public class BaseJpaService<T, R> {
        return (T) getRepository().findOne(id);
    }
    public List search(String filters) throws ParseException {
    public List<T> search(String filters) throws ParseException {
        URLQueryParser queryParser = createQueryParser("", filters, "");
        CriteriaQuery query = queryParser.makeCriteriaQuery();
@ -121,7 +109,7 @@ public class BaseJpaService<T, R> {
                .getResultList();
    }
    public List search(String filters, String sorts) throws ParseException {
    public List<T> search(String filters, String sorts) throws ParseException {
        URLQueryParser queryParser = createQueryParser("", filters, sorts);
        CriteriaQuery query = queryParser.makeCriteriaQuery();
@ -130,7 +118,7 @@ public class BaseJpaService<T, R> {
                .getResultList();
    }
    public List search(String fields, String filters, String sorts) throws ParseException {
    public List<T> search(String fields, String filters, String sorts) throws ParseException {
        URLQueryParser queryParser = createQueryParser(fields, filters, sorts);
        CriteriaQuery query = queryParser.makeCriteriaQuery();
        return entityManager
@ -138,7 +126,7 @@ public class BaseJpaService<T, R> {
                .getResultList();
    }
    public List search(String fields, String filters, String sorts, Integer page, Integer size) throws ParseException {
    public List<T> search(String fields, String filters, String sorts, Integer page, Integer size) throws ParseException {
        URLQueryParser queryParser = createQueryParser(fields, filters, sorts);
        CriteriaQuery query = queryParser.makeCriteriaQuery();
        if (page == null || page <= 0) {
@ -187,12 +175,10 @@ public class BaseJpaService<T, R> {
    }
    public Class<T> getEntityClass() {
        Type genType = this.getClass().getGenericSuperclass();
        Type[] parameters = ((ParameterizedType) genType).getActualTypeArguments();
        return (Class) parameters[0];
        return tClass;
    }
    protected <T> URLQueryParser createQueryParser(String fields, String filters, String orders) {
    public <T> URLQueryParser createQueryParser(String fields, String filters, String orders) {
        URLQueryParser queryParser = new URLQueryParser<T>(fields, filters, orders)
                .setEntityManager(entityManager)
                .setEntityClass(getEntityClass());
@ -200,7 +186,7 @@ public class BaseJpaService<T, R> {
        return queryParser;
    }
    protected <T> URLQueryParser createQueryParser(String filters) {
    public <T> URLQueryParser createQueryParser(String filters) {
        URLQueryParser queryParser = new URLQueryParser<T>(filters)
                .setEntityManager(entityManager)
                .setEntityClass(getEntityClass());
@ -208,7 +194,7 @@ public class BaseJpaService<T, R> {
        return queryParser;
    }
    protected Sort parseSorts(String sorter){
    public Sort parseSorts(String sorter){
        if (!StringUtils.isEmpty(sorter)) {
            String[] orderArray = sorter.split(",");
@ -222,27 +208,32 @@ public class BaseJpaService<T, R> {
        return null;
    }
    protected Session currentSession() {
        return entityManager.unwrap(Session.class);
    public JpaRepository getJpaRepository(){
        return (JpaRepository) SpringContext.getService(repoClass);
    }
    public PagingAndSortingRepository getRepository() {
        return (PagingAndSortingRepository) SpringContext.getService(repoClass);
    public R getRepository() {
        return SpringContext.getService(repoClass);
    }
    public JpaRepository getJpaRepository(){
        return (JpaRepository) SpringContext.getService(repoClass);
    public Session currentSession() {
        return entityManager.unwrap(Session.class);
    }
    public String getClzName(){
    public String getEntityName(){
        return getEntityClass().getName();
    }
    public String getEntityIdFiled(){
        EntityType entityType = entityManager.getMetamodel().entity(getEntityClass());
        javax.persistence.metamodel.Type type = entityType.getIdType();
        String s = entityType.getId(type.getJavaType()).getName();
        return s;
        return entityType.getId(type.getJavaType()).getName();
    }
    public String getEntityIdType(){
        EntityType entityType = entityManager.getMetamodel().entity(getEntityClass());
        javax.persistence.metamodel.Type type = entityType.getIdType();
        return type.getJavaType().getName();
    }
    /**
@ -286,12 +277,28 @@ public class BaseJpaService<T, R> {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    /**
     * 获取指定长度的随机数字字符串
     * @param length
     * @return
     */
    public String randomInt(int length) {
        String str = "0123456789";
        StringBuffer buffer = new StringBuffer();
        Random random = new Random();
        for(int i = 0; i < length; ++i) {
            int pos = random.nextInt(str.length());
            buffer.append(str.charAt(pos));
        }
        return buffer.toString();
    }
    /**
     * 获取指定长度的随机字符串
     * @param length
     * @return
     */
    protected String randomString(int length) {
    public String randomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuffer buffer = new StringBuffer();
        Random random = new Random();