扩展Koala的KoalaLegacyEntity,增强其CRUD方面的功能——持续更新中

这段时间在开发“镁光城”项目的时候使用到了开源的Koala系统,使用过程中有不少心得,进行了整理。 下面介绍的是“扩展Koala的KoalaLegacyEntity,增强其CRUD方面的功能” 使用过程中觉得Koala的基类KoalaLegacyEntity提供的CRUD方面的功能太简单,所以对其进行了扩展。 欢迎进行拍砖。

1.BaseEntity,继承KoalaLegacyEntity,对其进行了扩展

BaseEntity是主类,扩展的CRUD方法都在这个类里面,继承这个类的实体可直接使用扩展的方法,提高开发效率。 

另外,BaseEntity类使用到了两个工具类JPQLUtil和EntityUtil,下面会分别介绍。


package com.shanlan.basic.core.domain;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.dayatang.domain.Entity;
import org.dayatang.domain.InstanceFactory;
import org.dayatang.domain.JpqlQuery;
import org.dayatang.querychannel.QueryChannelService;
import org.dayatang.utils.Page;
import org.openkoala.koala.commons.domain.KoalaLegacyEntity;

import com.shanlan.common.util.EntityUtil;
import com.shanlan.common.util.JPQLUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by albertliu on 14/11/25.
 */
public class BaseEntity extends KoalaLegacyEntity {
    /**
     *
     */
    private static final long serialVersionUID = 6545100226409647983L;

    private static final Logger logger = LoggerFactory
            .getLogger(BaseEntity.class);

    protected static QueryChannelService getQueryChannelService() {
        QueryChannelService queryChannel = null;
        if (queryChannel == null) {
            queryChannel = InstanceFactory.getInstance(
                    QueryChannelService.class, "queryChannel");
        }
        return queryChannel;
    }

    /**
     * 获取业务主键。业务主键是判断相同类型的两个实体在业务上的等价性的依据。如果相同类型的两个
     * 实体的业务主键相同,则认为两个实体是相同的,代表同一个实体。
     * <p/>
     * 业务主键由实体的一个或多个属性组成。
     *
     * @return 组成业务主键的属性的数组。
     */
    @Override
    public String[] businessKeys() {
        return new String[0];
    }

    /**
     * 取得实体的Id。实体类的每个实例都必须有个唯一Id以标识自身。 实体Id必须是可序列化的。
     *
     * @return 实体实例的 Id.
     */
    @Override
    public Serializable getId() {
        return null;
    }

    /**
     * 更新一条记录中的一个属性
     *
     * @param entityName         要更新的实体名
     * @param setPropertyName    要更新的属性名
     * @param setPropertyValue   要更新的属性值
     * @param wherePropertyName  约束条件属性名
     * @param wherePropertyValue 约束条件属性值
     * @return
     */
    public static boolean updateOneRowOneProperty(String entityName,
                                                  String setPropertyName, Object setPropertyValue,
                                                  String wherePropertyName, Object wherePropertyValue) {
        boolean result = false;
        if (StringUtils.isNotBlank(entityName)
                && StringUtils.isNotBlank(setPropertyName)
                && setPropertyValue != null
                && StringUtils.isNotBlank(wherePropertyName)
                && wherePropertyValue != null) {

            StringBuffer JPQL = JPQLUtil.updatePropertyByProperty(entityName,
                    setPropertyName, wherePropertyName);
            JpqlQuery jpqlQuery = new JpqlQuery(getRepository(),
                    JPQL.toString());
            jpqlQuery.setParameters(setPropertyValue, wherePropertyValue);
            int updateCount = jpqlQuery.executeUpdate();
            if (updateCount == 1) {
                result = true;
            }
        }
        return result;
    }

    /**
     * 更新多个属性
     *
     * @param entityName             要更新的实体名
     * @param setPropertyAndValueMap 要更新的属性名与值Map
     * @param wherePropertyName      约束条件属性名
     * @param wherePropertyValue     约束条件属性值
     * @return
     */
    public static boolean update(String entityName,
                                 Map<String, Object> setPropertyAndValueMap,
                                 String wherePropertyName, Object wherePropertyValue) {
        if (StringUtils.isNotBlank(entityName)
                && MapUtils.isNotEmpty(setPropertyAndValueMap)
                && StringUtils.isNotBlank(wherePropertyName)
                && wherePropertyValue != null) {

            StringBuffer JPQL = JPQLUtil.updateAndSet(entityName);
            int i = 0;
            List<Object> conditionValues = new ArrayList<Object>();
            for (Map.Entry<String, Object> entry : setPropertyAndValueMap
                    .entrySet()) {
                String property = entry.getKey();
                Object value = entry.getValue();
                if (StringUtils.isBlank(property) && value == null) {
                    continue;
                }
                i++;
                if (i == 1) {
                    JPQL.append(JPQLUtil.appendEqualQuestionSign(entityName,
                            property));
                    conditionValues.add(value);
                } else if (i > 1) {
                    JPQL.append(JPQLUtil.appendCommaEqualQuestionSign(
                            entityName, property));
                    conditionValues.add(value);
                }
            }
            JPQL.append(JPQLUtil.whereEntityDotPropertyNameEqualQuestionSign(
                    entityName, wherePropertyName));
            conditionValues.add(wherePropertyValue);

            JpqlQuery jpqlQuery = new JpqlQuery(getRepository(),
                    JPQL.toString());
            jpqlQuery.setParameters(conditionValues);
            int updateCount = jpqlQuery.executeUpdate();
            logger.info("JPQL:'" + JPQL.toString() + "' conditionValues:'"
                    + StringUtils.join(conditionValues, ",") + "' UpdateCount:"
                    + updateCount);
            if ("id".equals(wherePropertyName)) {// 如果是根据Id更新,则只会更新一条记录
                return updateCount == 1;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 更新实体中不为null的字段
     *
     * @return
     * @throws IllegalAccessException
     */
    public Boolean update() throws IllegalAccessException {
        if (this.getId() != null) {
            Integer id = (Integer) this.getId();
            Map<String, Object> setPropertyValueMap = EntityUtil
                    .getNotNullAndIdPropertyNameAndValueMap(this);
            return update(this.getClass().getSimpleName(), setPropertyValueMap,
                    id);
        } else if (this.getId() == null) {
            throw new NullPointerException("id不能为空");
        }
        return false;
    }

    /**
     * 根据Id更新多个属性
     *
     * @param entityName             要更新的实体名
     * @param setPropertyAndValueMap 要更新的属性名与值Map
     * @param id                     id的值
     * @return
     */
    public static boolean update(String entityName,
                                 Map<String, Object> setPropertyAndValueMap, Integer id) {
        return update(entityName, setPropertyAndValueMap, "id", id);
    }

    /**
     * 更新一条记录中的一个属性
     *
     * @param entityName       要更新的实体名
     * @param setPropertyName  要更新的属性名
     * @param setPropertyValue 要更新的属性值
     * @param id               id值
     * @return
     */
    public static boolean updateOneRowOneProperty(String entityName,
                                                  String setPropertyName, Object setPropertyValue, Integer id) {
        boolean result = false;
        if (StringUtils.isNotBlank(entityName)
                && StringUtils.isNotBlank(setPropertyName)
                && setPropertyValue != null && id != null) {

            StringBuffer JPQL = JPQLUtil.updatePropertyByProperty(entityName,
                    setPropertyName, "id");
            JpqlQuery jpqlQuery = new JpqlQuery(getRepository(),
                    JPQL.toString());
            jpqlQuery.setParameters(setPropertyValue, id);
            int updateCount = jpqlQuery.executeUpdate();
            if (updateCount == 1) {
                result = true;
            }
        }
        return result;
    }

    /**
     * 根据查询条件列出实体
     *
     * @param <T>                 实体所属的类型
     * @param clazz               实体所属的类
     * @param wherePropertyName   条件属性名
     * @param wherePropertyValues 条件属性值列表
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> List<T> list(Class<T> clazz,
                                                  String wherePropertyName, Collection<?> wherePropertyValues) {
        List<T> entityList = new ArrayList<T>();
        if (clazz != null && CollectionUtils.isNotEmpty(wherePropertyValues)) {
            StringBuffer JPQL = JPQLUtil.selectByPropertyIn(clazz,
                    wherePropertyName, wherePropertyValues);
            entityList = getRepository().createJpqlQuery(JPQL.toString())
                    .list();
        }
        return entityList;
    }

    /**
     * 根据查询条件列出实体
     *
     * @param <T>                  实体所属的类型
     * @param clazz                实体所属的类
     * @param wherePropertyName2   条件属性名
     * @param wherePropertyValues2 条件属性值列表
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> List<T> list(Class<T> clazz,
                                                  String wherePropertyName1, Object wherePropertyValue1,
                                                  String wherePropertyName2, Collection<?> wherePropertyValues2) {
        List<T> entityList = new ArrayList<T>();
        String entityName = clazz.getSimpleName();
        StringBuffer JPQL = JPQLUtil.selectEntity(entityName);
        JPQL.append(JPQLUtil.fromEntity(entityName));
        JPQL.append(JPQLUtil.whereIdentity());
        List<Object> conditionValues = new ArrayList<Object>();
        if (StringUtils.isNotBlank(wherePropertyName1)
                && wherePropertyValue1 != null) {
            JPQL.append(JPQLUtil.andPropertyEqualQuestionSign(entityName,
                    wherePropertyName1));
            conditionValues.add(wherePropertyValue1);
        }
        if (StringUtils.isNotBlank(wherePropertyName2)
                && CollectionUtils.isNotEmpty(wherePropertyValues2)) {
            JPQL.append(JPQLUtil.andPropertyIn(entityName, wherePropertyName2,
                    wherePropertyValues2));
        }

        entityList = getRepository().createJpqlQuery(JPQL.toString())
                .setParameters(conditionValues).list();

        return entityList;
    }

    /**
     * 根据查询条件列出自关联的实体,JQPL语句形如: Select entityB From entity As entityA,entity As
     * entityB Where
     * entityA.entityNameARePropertyName=entityB.entityNameBRePropertyName And
     * entityA.entityAWherePropertyName1=entityAWherePropertyValue1 And
     * entityA.entityAWherePropertyName2 In (entityAWherePropertyValues2)
     *
     * @param <T>                         实体所属的类型
     * @param clazz                       实体所属的类
     * @param entityNameARePropertyName   进行自关联的属性名
     * @param entityNameBRePropertyName   进行自关联的属性名
     * @param entityAWherePropertyName1   entityB条件属性名
     * @param entityAWherePropertyValue1  entityB条件属性值列表
     * @param entityAWherePropertyName2   entityB条件属性名
     * @param entityAWherePropertyValues2 entityB条件属性值列表
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> List<T> listSelfRelation(Class<T> clazz,
                                                              String entityNameARePropertyName, String entityNameBRePropertyName,
                                                              String entityAWherePropertyName1,
                                                              Object entityAWherePropertyValue1,
                                                              String entityAWherePropertyName2,
                                                              Collection<?> entityAWherePropertyValues2) {
        List<T> entityList = new ArrayList<T>();

        String entityNameA = EntityUtil.getEntityNameAppendA(clazz);
        String entityNameB = EntityUtil.getEntityNameAppendB(clazz);

        StringBuffer JPQL = JPQLUtil.selectEntity(entityNameB);
        JPQL.append(JPQLUtil.fromTowEntities(clazz));
        JPQL.append(JPQLUtil.whereIdentity());
        if (StringUtils.isNotBlank(entityNameARePropertyName)
                && StringUtils.isNotBlank(entityNameBRePropertyName)) {
            JPQL.append(JPQLUtil.andTwoEntityRelation(entityNameA,
                    entityNameARePropertyName, entityNameB,
                    entityNameBRePropertyName));
        }
        List<Object> conditionValues = new ArrayList<Object>();
        if (StringUtils.isNotBlank(entityAWherePropertyName1)
                && entityAWherePropertyValue1 != null) {
            JPQL.append(JPQLUtil.andPropertyEqualQuestionSign(entityNameA,
                    entityAWherePropertyName1));
            conditionValues.add(entityAWherePropertyValue1);
        }
        if (StringUtils.isNotBlank(entityAWherePropertyName2)
                && CollectionUtils.isNotEmpty(entityAWherePropertyValues2)) {
            JPQL.append(JPQLUtil.andPropertyIn(entityNameA,
                    entityAWherePropertyName2, entityAWherePropertyValues2));
        }

        entityList = getRepository().createJpqlQuery(JPQL.toString())
                .setParameters(conditionValues).list();

        return entityList;
    }

    /**
     * 根据查询条件列出自关联的实体,JQPL语句形如: Select entityB From entity As entityA,entity As
     * entityB Where
     * entityA.entityNameARePropertyName=entityB.entityNameBRePropertyName And
     * entityA.entityAWherePropertyName1=entityAWherePropertyValue1
     *
     * @param <T>                       实体所属的类型
     * @param clazz                     实体所属的类
     * @param entityAWherePropertyName  entityB条件属性名
     * @param entityAWherePropertyValue entityB条件属性值列
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> List<T> listSelfRelation(Class<T> clazz,
                                                              String entityNameARePropertyName, String entityNameBRePropertyName,
                                                              String entityAWherePropertyName, Object entityAWherePropertyValue) {
        return listSelfRelation(clazz, entityNameARePropertyName,
                entityNameBRePropertyName, entityAWherePropertyName,
                entityAWherePropertyValue, null, null);
    }

    /**
     * 根据id列表列出实体
     *
     * @param <T>   实体所属的类型
     * @param clazz 实体所属的类
     * @param ids   id列表
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> List<T> list(Class<T> clazz,
                                                  Collection<?> ids) {
        List<T> entityList = new ArrayList<T>();
        if (clazz != null && CollectionUtils.isNotEmpty(ids)) {
            StringBuffer JPQL = JPQLUtil.selectByPropertyIn(clazz, "id", ids);
            entityList = getRepository().createJpqlQuery(JPQL.toString())
                    .list();
        }
        return entityList;
    }

    /**
     * @param <T>                 实体所属的类型
     * @param clazz               实体所属的类
     * @param wherePropertyName   条件属性名
     * @param wherePropertyValues 条件属性值列表
     * @return 符合条件的Id与实体自身的HashMap
     */
    public static <T extends Entity> Map<Integer, T> getIdAndSelfMap(
            Class<T> clazz, String wherePropertyName,
            List<?> wherePropertyValues) {
        Map<Integer, T> idAndSelfMap = new HashMap<Integer, T>();
        List<T> entityList = list(clazz, wherePropertyName, wherePropertyValues);
        for (T entity : entityList) {
            idAndSelfMap.put((Integer) entity.getId(), entity);
        }
        return idAndSelfMap;
    }

    /**
     * 分页查询实体
     *
     * @param <T>                 实体所属的类型
     * @param clazz               实体所属的类
     * @param wherePropertyName   条件属性名
     * @param wherePropertyValue  条件属性值
     * @param pageIndex           当前页
     * @param pageSize            每页显示的数据量
     * @param orderByPropertyName 进行排序的属性名,为null则不排序
     * @param isDESC              是否按倒序排列,为null或false按升序排序
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> Page<T> page(Class<T> clazz,
                                                  int pageIndex, int pageSize, String wherePropertyName,
                                                  Object wherePropertyValue, String orderByPropertyName,
                                                  Boolean isDESC) {
        return page(clazz, wherePropertyName, wherePropertyValue, null, null,
                pageIndex, pageSize, orderByPropertyName, isDESC);

    }

    /**
     * 分页查询实体
     *
     * @param <T>                 实体所属的类型
     * @param clazz               实体所属的类
     * @param wherePropertyName   条件属性名
     * @param wherePropertyValues 条件属性值列表
     * @param pageIndex           当前页
     * @param pageSize            每页显示的数据量
     * @param orderByPropertyName 进行排序的属性名,为null则不排序
     * @param isDESC              是否按倒序排列,为null或false按升序排序
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> Page<T> page(Class<T> clazz,
                                                  String wherePropertyName, Collection<?> wherePropertyValues,
                                                  int pageIndex, int pageSize, String orderByPropertyName,
                                                  Boolean isDESC) {
        Page<T> entityPage = new Page<T>(0, 0, pageSize, new ArrayList<T>());
        String entityName = EntityUtil.getEntityName(clazz);
        StringBuffer JPQL = JPQLUtil.selectByPropertyIn(entityName,
                wherePropertyName, wherePropertyValues);
        if (StringUtils.isNotBlank(JPQL)
                && CollectionUtils.isNotEmpty(wherePropertyValues)) {
            if (StringUtils.isNotBlank(orderByPropertyName)) {
                JPQL.append(JPQLUtil.orderBy(entityName, orderByPropertyName));
                if (isDESC != null && isDESC) {
                    JPQL.append(JPQLUtil.orderDESC());
                }
            }
            entityPage = getQueryChannelService()
                    .createJpqlQuery(JPQL.toString())
                    .setPage(pageIndex, pageSize).pagedList();
        }
        return entityPage;
    }

    /**
     * 分页查询实体
     *
     * @param <T>                  实体所属的类型
     * @param clazz                实体所属的类
     * @param wherePropertyName1   条件1属性名
     * @param wherePropertyValue1  条件1属性值列表
     * @param wherePropertyName2   条件2属性名
     * @param wherePropertyValues2 条件2属性值列表
     * @param pageIndex            当前页
     * @param pageSize             每页显示的数据量
     * @param orderByPropertyName  进行排序的属性名,为null则不排序
     * @param isDESC               是否按倒序排列,为null或false按升序排序
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> Page<T> page(Class<T> clazz,
                                                  String wherePropertyName1, Object wherePropertyValue1,
                                                  String wherePropertyName2, Collection<?> wherePropertyValues2,
                                                  int pageIndex, int pageSize, String orderByPropertyName,
                                                  Boolean isDESC) {
        Page<T> entityPage = new Page<T>(0, 0, pageSize, new ArrayList<T>());
        String entityName = EntityUtil.getEntityName(clazz);
        StringBuffer JPQL = JPQLUtil.selectEntity(entityName);
        JPQL.append(JPQLUtil.fromEntity(entityName));
        JPQL.append(JPQLUtil.whereIdentity());
        List<Object> conditionValues = new ArrayList<Object>();
        if (StringUtils.isNotBlank(wherePropertyName1)
                && wherePropertyValue1 != null) {
            JPQL.append(JPQLUtil.andPropertyEqualQuestionSign(entityName,
                    wherePropertyName1));
            conditionValues.add(wherePropertyValue1);
        }
        if (StringUtils.isNotBlank(wherePropertyName2)
                && CollectionUtils.isNotEmpty(wherePropertyValues2)) {
            JPQL.append(JPQLUtil.andPropertyIn(entityName, wherePropertyName2,
                    wherePropertyValues2));
        }

        if (StringUtils.isNotBlank(orderByPropertyName)) {
            JPQL.append(JPQLUtil.orderBy(entityName, orderByPropertyName));
            if (isDESC != null && isDESC) {
                JPQL.append(JPQLUtil.orderDESC());
            }
        }
        entityPage = getQueryChannelService().createJpqlQuery(JPQL.toString())
                .setParameters(conditionValues).setPage(pageIndex, pageSize)
                .pagedList();
        return entityPage;
    }

    /**
     * 执行 Delete From entityName where propertyName In (propertyValues)
     * 这种类型的删除语句
     *
     * @param entityName
     * @param propertyName
     * @param propertyValue
     * @return
     */
    public static boolean delete(String entityName, String propertyName,
                                 Object propertyValue) {
        if (propertyValue != null) {
            StringBuffer JPQL = JPQLUtil.deleteByProperty(entityName,
                    propertyName);
            JpqlQuery jpqlQuery = new JpqlQuery(getRepository(),
                    JPQL.toString());
            jpqlQuery.setParameters(propertyValue);
            int deleteCount = jpqlQuery.executeUpdate();
            logger.info("JPQL:'" + JPQL.toString() + "' propertyValue1:'"
                    + propertyValue + "' DeleteCount:" + deleteCount);
            return true;
        }
        return false;
    }

    /**
     * 执行 Delete From entityName where propertyName = ? 这种类型的删除语句
     *
     * @param clazz
     * @param propertyName
     * @param propertyValue
     * @return
     */
    public static boolean delete(Class clazz, String propertyName,
                                 Object propertyValue) {
        if (clazz != null && propertyValue != null) {
            String entityName = clazz.getSimpleName();
            StringBuffer JPQL = JPQLUtil.deleteByProperty(entityName,
                    propertyName);
            JpqlQuery jpqlQuery = new JpqlQuery(getRepository(),
                    JPQL.toString());
            jpqlQuery.setParameters(propertyValue);
            int deleteCount = jpqlQuery.executeUpdate();
            logger.info("JPQL:'" + JPQL.toString() + "' propertyValue1:'"
                    + propertyValue + "' DeleteCount:" + deleteCount);
            return true;
        }
        return false;
    }

    /**
     * 执行 Delete From entityName where propertyName In (propertyValues)
     * 这种类型的删除语句
     *
     * @param entityName
     * @param propertyName
     * @param propertyValues
     * @return
     */
    public static boolean delete(String entityName, String propertyName,
                                 Collection<?> propertyValues) {
        if (CollectionUtils.isNotEmpty(propertyValues)) {
            StringBuffer JPQL = JPQLUtil.deleteByPropertyIn(entityName,
                    propertyName, propertyValues);
            JpqlQuery jpqlQuery = new JpqlQuery(getRepository(),
                    JPQL.toString());
            int deleteCount = jpqlQuery.executeUpdate();
            logger.info("JPQL:'" + JPQL.toString() + "' DeleteCount:"
                    + deleteCount);
            if (deleteCount == propertyValues.size()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 执行 Delete From entityName where propertyName In (propertyValues)
     * 这种类型的删除语句
     *
     * @param entityName
     * @param propertyName1
     * @param propertyValue1
     * @param propertyName2
     * @param propertyValues2
     * @return
     */
    public static boolean delete(String entityName, String propertyName1,
                                 Object propertyValue1, String propertyName2,
                                 Collection<?> propertyValues2) {
        if ((StringUtils.isNotBlank(propertyName1) && StringUtils
                .isNotBlank(propertyName2))
                && (propertyValue1 != null || CollectionUtils
                .isNotEmpty(propertyValues2))) {

            StringBuffer JPQL = JPQLUtil.deleteByProperty(entityName,
                    propertyName1);
            JPQL.append(JPQLUtil.andPropertyIn(entityName, propertyName2,
                    propertyValues2));

            JpqlQuery jpqlQuery = new JpqlQuery(getRepository(),
                    JPQL.toString());
            jpqlQuery.setParameters(propertyValue1);
            int deleteCount = jpqlQuery.executeUpdate();
            logger.info("JPQL:'" + JPQL.toString() + "' propertyValue1:'"
                    + propertyValue1 + "' DeleteCount:" + deleteCount);

            return true;
        }
        return false;
    }

    /**
     * 执行 Delete From entityName where propertyName In (propertyValues)
     * 这种类型的删除语句
     *
     * @param clazz
     * @param propertyName1
     * @param propertyValue1
     * @param propertyName2
     * @param propertyValues2
     * @return
     */
    public static boolean delete(Class clazz, String propertyName1,
                                 Object propertyValue1, String propertyName2,
                                 Collection<?> propertyValues2) {
        if ((StringUtils.isNotBlank(propertyName1) && StringUtils
                .isNotBlank(propertyName2))
                && (propertyValue1 != null || CollectionUtils
                .isNotEmpty(propertyValues2))) {
            String entityName = clazz.getSimpleName();
            StringBuffer JPQL = JPQLUtil.deleteByProperty(entityName,
                    propertyName1);
            JPQL.append(JPQLUtil.andPropertyIn(entityName, propertyName2,
                    propertyValues2));

            JpqlQuery jpqlQuery = new JpqlQuery(getRepository(),
                    JPQL.toString());
            jpqlQuery.setParameters(propertyValue1);
            int deleteCount = jpqlQuery.executeUpdate();
            logger.info("JPQL:'" + JPQL.toString() + "' propertyValue1:'"
                    + propertyValue1 + "' DeleteCount:" + deleteCount);

            return true;
        }
        return false;
    }

    /**
     * 执行 Delete From entityName where id In (ids) 这种类型的删除语句
     *
     * @param entityName
     * @param ids
     * @return
     */
    public static boolean delete(String entityName, Collection<Integer> ids) {
        return delete(entityName, "id", ids);
    }

    /**
     * 执行 Delete From entityName where propertyName In (propertyValues)
     * 这种类型的删除语句
     *
     * @param clazz          实体所属的类
     * @param propertyName   属性名
     * @param propertyValues 属性值列表
     * @return
     */
    public static boolean delete(Class clazz, String propertyName,
                                 Collection<?> propertyValues) {
        return delete(clazz.getSimpleName(), propertyName, propertyValues);
    }

    /**
     * 执行 Delete From entityName where id In (ids) 这种类型的删除语句
     *
     * @param clazz 实体所属的类
     * @param ids   id列表
     * @return
     */
    public static boolean delete(Class clazz, Collection<Integer> ids) {
        return delete(clazz.getSimpleName(), "id", ids);
    }

}


1.1. JPQLUtil,用于拼接JPQL语句的工具类


package com.shanlan.common.util;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

/**
 * Created by albertliu on 14-10-20.
 */
public class JPQLUtil {

	/**
	 * 得到形如select xx from xx where xxx =?的Sql语句
	 *
	 * @param entityName
	 * @param wherePropertyName
	 * @return
	 */
	public static StringBuffer selectByProperty(String entityName,
			String wherePropertyName) {
		StringBuffer JPQL = new StringBuffer();
		if (StringUtils.isNotBlank(entityName)
				&& StringUtils.isNotBlank(wherePropertyName)) {
			JPQL.append(selectEntity(entityName));
			JPQL.append(fromEntity(entityName));
			JPQL.append(whereEntityDotPropertyNameEqualQuestionSign(entityName,
					wherePropertyName));
		}
		return JPQL;
	}

	/**
	 * 得到形如select xx from xx where xxx in()的Sql语句
	 *
	 * @param clazz
	 * @param propertyName
	 * @param propertyValues
	 * @return
	 */
	public static StringBuffer selectByPropertyIn(Class clazz,
			String propertyName, Iterable<?> propertyValues) {
		StringBuffer JPQL = new StringBuffer();
		if (clazz != null && propertyValues != null) {
			String entityName = clazz.getSimpleName();
			JPQL.append(selectEntity(entityName));
			JPQL.append(fromEntity(entityName));
			JPQL.append(whereEntityDotPropertyNameInValue(entityName,
					propertyName, propertyValues));
		}
		return JPQL;
	}

	/**
	 * 得到形如select xx from xx where xxx in()的Sql语句
	 *
	 * @param entityName
	 * @param wherePropertyName
	 * @param wherePropertyValues
	 * @return
	 */
	public static StringBuffer selectByPropertyIn(String entityName,
			String wherePropertyName, Iterable<?> wherePropertyValues) {
		StringBuffer JPQL = new StringBuffer();
		if (StringUtils.isNotBlank(entityName)
				&& StringUtils.isNotBlank(wherePropertyName)
				&& wherePropertyValues != null) {
			JPQL.append(selectEntity(entityName));
			JPQL.append(fromEntity(entityName));
			JPQL.append(whereEntityDotPropertyNameInValue(entityName,
					wherePropertyName, wherePropertyValues));
		}
		return JPQL;
	}

	/**
	 * 得到形如select xx from xx where xxx not in()的Sql语句
	 *
	 * @param clazz
	 * @param propertyName
	 * @param propertyValues
	 * @return
	 */
	public static StringBuffer selectByPropertyNotIn(Class clazz,
			String propertyName, java.lang.Iterable<?> propertyValues) {
		StringBuffer JPQL = new StringBuffer();
		if (clazz != null && propertyValues != null
				&& StringUtils.isNotBlank(propertyName)) {
			String entityName = clazz.getSimpleName();
			JPQL.append("Select " + entityName);
			JPQL.append(" From " + entityName + " " + entityName);
			JPQL.append(" Where " + propertyName + " Not In ('"
					+ StringUtils.join(propertyValues, "','") + "')");
		}
		return JPQL;
	}

	public static StringBuffer selectEntity(Class clazz) {
		StringBuffer JPQL = new StringBuffer();
		if (clazz != null) {
			JPQL.append("Select " + clazz.getSimpleName());
		}
		return JPQL;
	}

	public static StringBuffer selectEntity(String entityName) {
		StringBuffer JPQL = new StringBuffer();
		if (StringUtils.isNotBlank(entityName)) {
			JPQL.append("Select " + entityName + " ");
		}
		return JPQL;
	}

	/**
	 * 返回形如 Delete From xxx As xxx这种类型的StringBuffer
	 *
	 * @param entityName
	 * @return
	 */
	public static StringBuffer deleteEntity(String entityName) {
		StringBuffer JPQL = new StringBuffer();
		if (StringUtils.isNotBlank(entityName)) {
			JPQL.append("Delete From "
					+ EntityUtil.getEntityNameAndAlias(entityName) + " ");
		}
		return JPQL;
	}

	public static String fromEntity(String entity) {
		return " From " + entity + " As " + entity;
	}

	/**
	 * 返回形如 Select entity From entity as entity
	 *
	 * @param entityName
	 * @return
	 */
	public static StringBuffer selectEntityFromEntity(String entityName) {
		StringBuffer JPQL = selectEntity(entityName);
		JPQL.append(fromEntity(entityName));
		return JPQL;
	}

	/**
	 * 返回形如 From EntityA As EntityA,EntityB As EntityB 这样的字符串
	 *
	 * @param entity1
	 * @param entity2
	 * @return
	 */
	public static String fromTowEntities(String entity1, String entity2) {
		return fromEntity(entity1) + " , " + entity2 + " As " + entity2;
	}

	/**
	 * 返回形如 From Entity As EntityA,Entity As EntityB 这样的字符串
	 *
	 * @param entity1
	 * @param entity2
	 * @return
	 */
	public static String fromTowEntities(String entityName, String entityNameA,
			String entityNameB) {
		return entityName + " As " + entityNameA + " , " + entityName + " As "
				+ entityNameB;
	}

	/**
	 * 返回形如 From Entity As EntityA,Entity As EntityB 这样的字符串
	 *
	 * @param entity1
	 * @param entity2
	 * @return
	 */
	public static String fromTowEntities(Class clazz, String entityNameA,
			String entityNameB) {
		String entityName = EntityUtil.getEntityName(clazz);
		return entityName + " As " + entityNameA + " , " + entityName + " As "
				+ entityNameB;
	}

	/**
	 * 返回形如 From Entity As EntityA,Entity As EntityB 这样的字符串
	 *
	 * @param entity1
	 * @param entity2
	 * @return
	 */
	public static String fromTowEntities(Class clazz) {
		String entityName = EntityUtil.getEntityName(clazz);
		return " From "+entityName + " As " + EntityUtil.getEntityNameAppendA(clazz)
				+ " , " + entityName + " As "
				+ EntityUtil.getEntityNameAppendB(clazz);
	}

	/**
	 * 返回形如 From EntityA As EntityA 这样的字符串
	 *
	 * @param clazz
	 * @return
	 */
	public static String fromEntity(Class clazz) {
		return " From " + EntityUtil.getEntityNameAndAlias(clazz);
	}

	/**
	 * 返回形如 From EntityA As EntityA,EntityB As EntityB 这样的字符串
	 *
	 * @param clazz1
	 * @param clazz2
	 * @return
	 */
	public static String fromTowEntities(Class clazz1, Class clazz2) {
		return fromEntity(clazz1) + " , "
				+ EntityUtil.getEntityNameAndAlias(clazz2);
	}

	/**
	 * 返回形如 Update EntityA As EntityA 这样的字符串
	 *
	 * @param clazz
	 * @return
	 */
	public static StringBuffer update(Class clazz) {
		StringBuffer JPQL = new StringBuffer();
		JPQL.append("Update ");
		JPQL.append(EntityUtil.getEntityNameAndAlias(clazz));
		return JPQL;
	}

	/**
	 * 返回形如 Update EntityA As EntityA Set 这样的字符串
	 *
	 * @param clazz
	 * @return
	 */
	public static StringBuffer updateAndSet(Class clazz) {
		StringBuffer JPQL = new StringBuffer();
		JPQL.append("Update ");
		JPQL.append(EntityUtil.getEntityNameAndAlias(clazz));
		JPQL.append(" Set ");
		return JPQL;
	}

	/**
	 * 返回形如 Update EntityA As EntityA Set 这样的字符串
	 *
	 * @param entityName
	 * @return
	 */
	public static StringBuffer updateAndSet(String entityName) {
		StringBuffer JPQL = new StringBuffer();
		JPQL.append("Update ");
		JPQL.append(EntityUtil.getEntityNameAndAlias(entityName));
		JPQL.append(" Set ");
		return JPQL;
	}

	/**
	 * 返回形如 Update EntityA As EntityA 这样的字符串
	 *
	 * @param entityName
	 * @return
	 */
	public static StringBuffer update(String entityName) {
		StringBuffer JPQL = new StringBuffer();
		JPQL.append("Update ");
		JPQL.append(EntityUtil.getEntityNameAndAlias(entityName));
		return JPQL;
	}

	/**
	 * @param clazz
	 * @param propertyName
	 * @param columnValue
	 * @param id
	 * @return
	 */
	public static StringBuffer updatePropertyById(Class clazz,
			String propertyName, String columnValue, Integer id) {
		StringBuffer JPQL = new StringBuffer();
		if (clazz != null && StringUtils.isNotBlank(propertyName)) {
			String entityName = clazz.getSimpleName();
			JPQL.append("Update " + entityName + " " + entityName);
			JPQL.append(" Set " + propertyName + "='" + columnValue + "'");
			JPQL.append(" Where id='" + id + "'");
		}
		return JPQL;
	}

	/**
	 * 返回形如 Update entity AS entity set setPropertyName=? Where
	 * wherePropertyName=? 这种类型的JPQL语句
	 *
	 * @param clazz
	 * @param setPropertyName
	 * @param wherePropertyName
	 * @return
	 */
	public static StringBuffer updatePropertyByProperty(Class clazz,
			String setPropertyName, String wherePropertyName) {
		StringBuffer JPQL = new StringBuffer();
		if (clazz != null && StringUtils.isNotBlank(setPropertyName)
				&& StringUtils.isNotBlank(wherePropertyName)) {
			String entityName = EntityUtil.getEntityName(clazz);
			JPQL = update(entityName);
			JPQL.append(setEqualQuestionSign(entityName, setPropertyName));
			JPQL.append(whereEntityDotPropertyNameEqualQuestionSign(entityName,
					wherePropertyName));
		}
		return JPQL;
	}

	/**
	 * 返回形如 Update entity AS entity set setPropertyName=? Where
	 * wherePropertyName=? 这种类型的JPQL语句
	 *
	 * @param entityName
	 * @param setPropertyName
	 * @param wherePropertyName
	 * @return
	 */
	public static StringBuffer updatePropertyByProperty(String entityName,
			String setPropertyName, String wherePropertyName) {
		StringBuffer JPQL = new StringBuffer();
		if (StringUtils.isNotBlank(entityName)
				&& StringUtils.isNotBlank(setPropertyName)
				&& StringUtils.isNotBlank(wherePropertyName)) {
			JPQL = update(entityName);
			JPQL.append(setEqualQuestionSign(entityName, setPropertyName));
			JPQL.append(whereEntityDotPropertyNameEqualQuestionSign(entityName,
					wherePropertyName));
		}
		return JPQL;
	}

	/**
	 * 得到形如select xx from xx where id in()的Sql语句
	 *
	 * @param clazz
	 * @param ids
	 * @return
	 */
	public static StringBuffer selectByIdIn(Class clazz, List<Integer> ids) {
		return selectByPropertyIn(clazz, "id", ids);
	}

	/**
	 * 得到形如select xx from xx where id in()的Sql语句
	 *
	 * @param entityName
	 * @param ids
	 * @return
	 */
	public static StringBuffer selectByIdIn(String entityName, List<Integer> ids) {
		return selectByPropertyIn(entityName, "id", ids);
	}

	/**
	 * 得到形如select xx from xx where id not in()的Sql语句
	 *
	 * @param clazz
	 * @param ids
	 * @return
	 */
	public static StringBuffer selectByIdNotIn(Class clazz, List<Integer> ids) {
		return selectByPropertyNotIn(clazz, "id", ids);
	}

	/**
	 * 在属性名后添加= ? 符号,比如属性名address的返回值会是 Entity.address= ?
	 *
	 * @param propertyName
	 * @return
	 */
	public static String appendEqualQuestionSign(String entityName,
			String propertyName) {
		return getEntityDotPropertyNameEqual(entityName, propertyName) + "? ";
	}

	/**
	 * 在属性名后添加 , Entity.property= ? 符号,比如属性名address的返回值会是 , Entity.address= ?
	 *
	 * @param entityName
	 * @param propertyName
	 * @return
	 */
	public static String appendCommaEqualQuestionSign(String entityName,
			String propertyName) {
		return ", " + getEntityDotPropertyNameEqual(entityName, propertyName)
				+ "? ";
	}

	/**
	 * 在属性名前添加And,在其后添加= ? 符号,比如属性名address的返回值会是And address= ?
	 *
	 * @param propertyName
	 * @return
	 */
	public static String andPropertyEqualQuestionSign(String entityName,
			String propertyName) {
		return " And "
				+ getEntityDotPropertyNameEqual(entityName, propertyName)
				+ "? ";
	}

	/**
	 * 在属性名前添加And,在其后添加!= ? 符号,比如属性名address的返回值会是And address!= ?
	 *
	 * @param propertyName
	 * @return
	 */
	public static String andPropertyNotEqualQuestionSign(String entityName,
			String propertyName) {
		return " And "
				+ getEntityDotPropertyNameNotEqual(entityName, propertyName)
				+ "? ";
	}

	/**
	 * 在属性名前添加Set,在其后添加= ? 符号,比如属性名address的返回值会是Set address= ?
	 *
	 * @param propertyName
	 * @return
	 */
	public static String setEqualQuestionSign(String entityName,
			String propertyName) {
		return " Set " + entityName + "." + propertyName + "= ? ";
	}

	/**
	 * 获取形如 Where entity.property=? 类型的字符串
	 *
	 * @param entityName
	 * @param propertyName
	 * @return
	 */
	public static String whereEntityDotPropertyNameEqualQuestionSign(
			String entityName, String propertyName) {
		return " Where "
				+ getEntityDotPropertyNameEqual(entityName, propertyName)
				+ "? ";
	}

	/**
	 * 在属性名后添加 like ? 符号,比如属性名address的返回值会是address like ?
	 *
	 * @param propertyName
	 * @return
	 */
	public static String andPropertyLikeQuestionSign(String entityName,
			String propertyName) {
		return " And " + getEntityDotPropertyName(entityName, propertyName)
				+ " Like ? ";
	}

	/**
	 * 在属性名后添加 In() 符号,比如属性名address的返回值会是address In ('XX','XX')
	 *
	 * @param propertyName
	 * @return
	 */
	public static String andPropertyIn(String entityName, String propertyName,
			Iterable<?> propertyValues) {
		return " And " + getEntityDotPropertyName(entityName, propertyName)
				+ " In ('" + StringUtils.join(propertyValues, "','") + "')";
	}

	/**
	 * 在属性名前添加And,在其后添加 Not In() 符号,比如属性名address的返回值会是 And address Not In
	 * ('XX','XX')
	 *
	 * @param propertyName
	 * @return
	 */
	public static String andPropertyNotIn(String entityName,
			String propertyName, Iterable<?> propertyValues) {
		return " And " + getEntityDotPropertyName(entityName, propertyName)
				+ " Not In ('" + StringUtils.join(propertyValues, "','") + "')";
	}

	/**
	 * 在属性名后添加>= ? 符号,比如属性名address的返回值会是address>= ?
	 *
	 * @param propertyName
	 * @return
	 */
	public static String andPropertyGreaterEqualQuestionSign(String entityName,
			String propertyName) {
		return " And " + getEntityDotPropertyName(entityName, propertyName)
				+ ">= ? ";
	}

	/**
	 * 在属性名后添加<= ? 符号,比如属性名address的返回值会是address<= ?
	 *
	 * @param propertyName
	 * @return
	 */
	public static String andPropertyLessEqualQuestionSign(String entityName,
			String propertyName) {
		return " And " + getEntityDotPropertyName(entityName, propertyName)
				+ "<= ? ";
	}

	/**
	 * 关联两个实体,即返回形如 And entity1.property1=entity2.property2
	 *
	 * @param entityName1
	 * @param propertyName1
	 * @param entityName2
	 * @param propertyName2
	 * @return
	 */
	public static String andTwoEntityRelation(String entityName1,
			String propertyName1, String entityName2, String propertyName2) {
		return " And "
				+ getEntityDotPropertyNameEqual(entityName1, propertyName1)
				+ getEntityDotPropertyName(entityName2, propertyName2);
	}

	/**
	 * 获取形如 UserDetail.userName 这种类型的字符串
	 *
	 * @param entityName
	 * @param propertyName
	 * @return
	 */
	public static String getEntityDotPropertyName(String entityName,
			String propertyName) {
		return " " + entityName + "." + propertyName + " ";
	}

	/**
	 * 获取形如 UserDetail.userName= 这种类型的字符串
	 *
	 * @param entityName
	 * @param propertyName
	 * @return
	 */
	public static String getEntityDotPropertyNameEqual(String entityName,
			String propertyName) {
		return " " + entityName + "." + propertyName + "=";
	}

	/**
	 * 获取形如 UserDetail.userName!= 这种类型的字符串
	 *
	 * @param entityName
	 * @param propertyName
	 * @return
	 */
	public static String getEntityDotPropertyNameNotEqual(String entityName,
			String propertyName) {
		return " " + entityName + "." + propertyName + "!=";
	}

	/**
	 * 获取形如 UserDetail.userName, 这种类型的字符串
	 *
	 * @param entityName
	 * @param propertyName
	 * @return
	 */
	public static String getEntityDotPropertyNameComma(String entityName,
			String propertyName) {
		return " " + entityName + "." + propertyName + ", ";
	}

	/**
	 * 获取形如 UserDetail.userName= 这种类型的字符串
	 *
	 * @param entityName
	 * @param propertyName
	 * @return
	 */
	public static String whereEntityDotPropertyNameEqual(String entityName,
			String propertyName) {
		return " Where " + entityName + "." + propertyName + "=";
	}

	// /**
	// * 获取形如 UserDetail.userName=? 这种类型的字符串
	// *
	// * @param entityName
	// * @param propertyName
	// * @return
	// */
	// public static String whereEntityDotPropertyNameEqualQuestionSign(
	// String entityName, String propertyName) {
	// return " Where" + entityName + "." + propertyName + "=?";
	// }

	/**
	 * 获取形如 UserDetail.userName='XX' 这种类型的字符串
	 *
	 * @param entityName
	 * @param propertyName
	 * @return
	 */
	public static String whereEntityDotPropertyNameEqualValue(
			String entityName, String propertyName, String propertyValue) {
		return " Where"
				+ getEntityDotPropertyNameEqual(entityName, propertyName)
				+ StringUtil.wrapSingleQuotes(propertyValue);
	}

	/**
	 * 在属性名后添加 In() 符号,比如属性名address的返回值会是address In ('XX','XX')
	 *
	 * @param propertyName
	 * @return
	 */
	public static String whereEntityDotPropertyNameInValue(String entityName,
			String propertyName, Iterable<?> propertyValues) {
		return " Where " + getEntityDotPropertyName(entityName, propertyName)
				+ " In ('" + StringUtils.join(propertyValues, "','") + "')";
	}

	/**
	 * 返回形如 Where property Not In ('') 这种类型的语句
	 *
	 * @param propertyName
	 * @return
	 */
	public static String whereEntityDotPropertyNameNotInValue(
			String entityName, String propertyName, Iterable<?> propertyValues) {
		return " Where " + getEntityDotPropertyName(entityName, propertyName)
				+ "Not In ('" + StringUtils.join(propertyValues, "','") + "')";
	}

	/**
	 * 获取形如 Select UserDetail.userName 这种类型的字符串
	 *
	 * @param entityName
	 * @param propertyName
	 * @return
	 */
	public static String selectEntityDotPropertyName(String entityName,
			String propertyName) {
		return "Select " + getEntityDotPropertyName(entityName, propertyName)
				+ " ";
	}

	/**
	 * 获取形如 Select Distinct UserDetail.userName 这种类型的字符串
	 *
	 * @param entityName
	 * @param propertyName
	 * @return
	 */
	public static String selectDistinctEntityDotPropertyName(String entityName,
			String propertyName) {
		return "Select Distinct"
				+ getEntityDotPropertyName(entityName, propertyName) + " ";
	}

	/**
	 * 获取形如 Select UserDetail.userName, 这种类型的字符串
	 *
	 * @param entityName
	 * @param propertyName
	 * @return
	 */
	public static String selectEntityDotPropertyNameComma(String entityName,
			String propertyName) {
		return "Select "
				+ getEntityDotPropertyNameComma(entityName, propertyName);
	}

	/**
	 * 关联两个实体,即返回形如 Where entity1.property1=entity2.property2
	 *
	 * @param entityName1
	 * @param propertyName1
	 * @param entityName2
	 * @param propertyName2
	 * @return
	 */
	public static String whereTwoEntityRelation(String entityName1,
			String propertyName1, String entityName2, String propertyName2) {
		return whereEntityDotPropertyNameEqual(entityName1, propertyName1)
				+ getEntityDotPropertyName(entityName2, propertyName2);
	}

	/**
	 * 返回 Where 1=1 这样的恒等式
	 *
	 * @return
	 */
	public static String whereIdentity() {
		return " Where 1=1 ";
	}

	/**
	 * 获取形如 Or entity.property=? 类型的字符串
	 *
	 * @param entityName
	 * @param propertyName
	 * @return
	 */
	public static String orEntityDotPropertyNameEqualQuestionSign(
			String entityName, String propertyName) {
		return " Or " + getEntityDotPropertyNameEqual(entityName, propertyName)
				+ "? ";
	}

	/**
	 * 获取形如 Order By entity.property 类型的字符串
	 *
	 * @param entityName
	 * @param orderByPropertyName
	 * @return
	 */
	public static String orderBy(String entityName, String orderByPropertyName) {
		return " Order By "
				+ getEntityDotPropertyName(entityName, orderByPropertyName);
	}

	public static String orderDESC() {
		return " DESC ";
	}

	/**
	 * 获取形如 Group By entity.property 类型的字符串
	 *
	 * @param entityName
	 * @param propertyName
	 * @return
	 */
	public static String groupBy(String entityName, String propertyName) {
		return " Group By "
				+ getEntityDotPropertyName(entityName, propertyName);
	}

	/**
	 * 得到形如 Delete from xx where xxx in()的Sql语句
	 *
	 * @param entityName
	 * @param wherePropertyName
	 * @param wherePropertyValues
	 * @return
	 */
	public static StringBuffer deleteByPropertyIn(String entityName,
			String wherePropertyName, Iterable<?> wherePropertyValues) {
		StringBuffer JPQL = new StringBuffer();
		if (StringUtils.isNotBlank(entityName)
				&& StringUtils.isNotBlank(wherePropertyName)
				&& wherePropertyValues != null) {
			JPQL.append(deleteEntity(entityName));
			JPQL.append(whereEntityDotPropertyNameInValue(entityName,
					wherePropertyName, wherePropertyValues));
		}
		return JPQL;
	}

	/**
	 * 得到形如 Delete from xx where xxx =?的Sql语句
	 *
	 * @param entityName
	 * @param wherePropertyName
	 * @return
	 */
	public static StringBuffer deleteByProperty(String entityName,
			String wherePropertyName) {
		StringBuffer JPQL = new StringBuffer();
		if (StringUtils.isNotBlank(entityName)
				&& StringUtils.isNotBlank(wherePropertyName)) {
			JPQL.append(deleteEntity(entityName));
			JPQL.append(whereEntityDotPropertyNameEqualQuestionSign(entityName,
					wherePropertyName));
		}
		return JPQL;
	}

	/**
	 * 得到形如 Delete from xx where id in()的Sql语句
	 *
	 * @param entityName
	 * @param wherePropertyValues
	 * @return
	 */
	public static StringBuffer deleteByIdIn(String entityName,
			Iterable<?> wherePropertyValues) {
		return deleteByPropertyIn(entityName, "id", wherePropertyValues);
	}

}


1.2. EntityUtil,用户实现获取实体名、属性等功能的工具类


package com.shanlan.common.util;

import org.openkoala.koala.commons.domain.KoalaLegacyEntity;

import javax.persistence.Column;
import javax.persistence.Table;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by albertliu on 14-10-20.
 */
public class EntityUtil {

    public static String getAllPropertyNameOfEntity(Class clazz) {
        if (clazz.isAnnotationPresent(Table.class)) {
            Table table = (Table) clazz.getAnnotation(Table.class);
            String tableName = table.name();
            Field[] fields = clazz.getDeclaredFields();
            StringBuffer allColumnName = new StringBuffer();
            for (Field field : fields) {
                if (field.isAnnotationPresent(Column.class)) {
                    Column column = field.getAnnotation(Column.class);
                    String columnName = column.name();
                    allColumnName.append(tableName + "." + columnName + ",");
                }
            }
            if (allColumnName.length() > 0) {
                return allColumnName.toString().substring(0,
                        allColumnName.length() - 1);
            }
        }
        return null;
    }


    public static String getEntityName(Class clazz) {
        return clazz.getSimpleName();
    }

    /**
     * 返回EntityName_A格式的实体名,比如实体是Goods,则返回Goods_A
     * 主要用于自己关联自己的查询
     *
     * @param clazz
     * @return
     */
    public static String getEntityNameAppendA(Class clazz) {
        return getEntityNameAppendA(getEntityName(clazz));
    }

    /**
     * 返回EntityName_B格式的实体名,比如实体是Goods,则返回Goods_B
     * 主要用于自己关联自己的查询
     *
     * @param clazz
     * @return
     */
    public static String getEntityNameAppendB(Class clazz) {
        return getEntityNameAppendB(getEntityName(clazz));
    }


    /**
     * 返回EntityName_A格式的实体名,比如实体是Goods,则返回Goods_A
     * 主要用于自己关联自己的查询
     *
     * @param entityName
     * @return
     */
    public static String getEntityNameAppendA(String entityName) {
        return entityName + "_A";
    }

    /**
     * 返回EntityName_B格式的实体名,比如实体是Goods,则返回Goods_B
     * 主要用于自己关联自己的查询
     *
     * @param entityName
     * @return
     */
    public static String getEntityNameAppendB(String entityName) {
        return entityName + "_B";
    }


    /**
     * 返回实体名及其Id,用于拼装JQPL语句,返回形式为entity.id,比如Goods.id.
     *
     * @param clazz
     * @return
     */
    public static String getEntityNameAndId(Class clazz) {
        String entityName = clazz.getSimpleName();
        return entityName + ".id";
    }


    public static String getEntityNameAndAlias(Class clazz) {
        String entityName = clazz.getSimpleName();
        return entityName + " As " + entityName;
    }


    public static String getEntityNameAndAlias(String entityName) {
        return entityName + " As " + entityName;
    }


    public static <T extends KoalaLegacyEntity> List<Integer> getIds(List<T> entityList) {
        List<Integer> ids = new ArrayList<Integer>();
        if (entityList != null && entityList.size() > 0) {
            for (T entity : entityList) {
                ids.add((Integer) entity.getId());
            }
        }
        return ids;
    }


    public static <T extends KoalaLegacyEntity> Map<Integer, T> getIdAndEntityMap(List<T> entityList) {
        Map<Integer, T> idAndEntityMap = new HashMap<Integer, T>();
        if (entityList != null && entityList.size() > 0) {
            for (T entity : entityList) {
                idAndEntityMap.put((Integer) entity.getId(), entity);
            }
        }
        return idAndEntityMap;
    }

    /**
     * 获取实体字段与值映射,不包括值为空的字段
     *
     * @param object
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> getNotNullPropertyNameAndValueMap(Object object) throws IllegalAccessException {
        Map<String, Object> paramValueMap = new HashMap<String, Object>();
        if (object != null) {
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(Column.class)) {
                    field.setAccessible(true);
                    String fieldName = field.getName();
                    Object fieldValue = field.get(object);
                    if (fieldValue != null) {
                        paramValueMap.put(fieldName, fieldValue);
                    }
                }
            }
        }
        return paramValueMap;
    }

    /**
     * 获取实体字段与值映射,不包括空值并且不包括id字段
     *
     * @param object
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> getNotNullAndIdPropertyNameAndValueMap(Object object) throws IllegalAccessException {
        Map<String, Object> paramValueMap = new HashMap<String, Object>();
        if (object != null) {
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(Column.class)) {
                    field.setAccessible(true);
                    String fieldName = field.getName();
                    if ("id".equals(fieldName)) {
                        continue;
                    }
                    Object fieldValue = field.get(object);
                    if (fieldValue != null) {
                        paramValueMap.put(fieldName, fieldValue);
                    }
                }
            }
        }
        return paramValueMap;
    }


    /**
     * 获取实体字段与值映射
     *
     * @param object
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> getPropertyNameAndValueMap(Object object) throws IllegalAccessException {
        Map<String, Object> paramValueMap = new HashMap<String, Object>();
        if (object != null) {
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(Column.class)) {
                    field.setAccessible(true);
                    String fieldName = field.getName();
                    Object fieldValue = field.get(object);
                    paramValueMap.put(fieldName, fieldValue);
                }
            }
        }
        return paramValueMap;
    }


}


2.查询功能示例


2.1 列表查询

分为“对应的方法”和使用示例两个方面进行介绍

2.1.1 对应方法


/**
     * 根据id列表列出实体
     *
     * @param <T>   实体所属的类型
     * @param clazz 实体所属的类
     * @param ids   id列表
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> List<T> list(Class<T> clazz,
                                                  Collection<?> ids) {
        List<T> entityList = new ArrayList<T>();
        if (clazz != null && CollectionUtils.isNotEmpty(ids)) {
            StringBuffer JPQL = JPQLUtil.selectByPropertyIn(clazz, "id", ids);
            entityList = getRepository().createJpqlQuery(JPQL.toString())
                    .list();
        }
        return entityList;
    }
    
    /**
     * 根据查询条件列出实体
     *
     * @param <T>                 实体所属的类型
     * @param clazz               实体所属的类
     * @param wherePropertyName   条件属性名
     * @param wherePropertyValues 条件属性值列表
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> List<T> list(Class<T> clazz,
                                                  String wherePropertyName, Collection<?> wherePropertyValues) {
        List<T> entityList = new ArrayList<T>();
        if (clazz != null && CollectionUtils.isNotEmpty(wherePropertyValues)) {
            StringBuffer JPQL = JPQLUtil.selectByPropertyIn(clazz,
                    wherePropertyName, wherePropertyValues);
            entityList = getRepository().createJpqlQuery(JPQL.toString())
                    .list();
        }
        return entityList;
    }

    /**
     * 根据查询条件列出实体
     *
     * @param <T>                  实体所属的类型
     * @param clazz                实体所属的类
     * @param wherePropertyName2   条件属性名
     * @param wherePropertyValues2 条件属性值列表
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> List<T> list(Class<T> clazz,
                                                  String wherePropertyName1, Object wherePropertyValue1,
                                                  String wherePropertyName2, Collection<?> wherePropertyValues2) {
        List<T> entityList = new ArrayList<T>();
        String entityName = clazz.getSimpleName();
        StringBuffer JPQL = JPQLUtil.selectEntity(entityName);
        JPQL.append(JPQLUtil.fromEntity(entityName));
        JPQL.append(JPQLUtil.whereIdentity());
        List<Object> conditionValues = new ArrayList<Object>();
        if (StringUtils.isNotBlank(wherePropertyName1)
                && wherePropertyValue1 != null) {
            JPQL.append(JPQLUtil.andPropertyEqualQuestionSign(entityName,
                    wherePropertyName1));
            conditionValues.add(wherePropertyValue1);
        }
        if (StringUtils.isNotBlank(wherePropertyName2)
                && CollectionUtils.isNotEmpty(wherePropertyValues2)) {
            JPQL.append(JPQLUtil.andPropertyIn(entityName, wherePropertyName2,
                    wherePropertyValues2));
        }

        entityList = getRepository().createJpqlQuery(JPQL.toString())
                .setParameters(conditionValues).list();

        return entityList;
    }

    /**
     * 根据查询条件列出自关联的实体,JQPL语句形如: Select entityB From entity As entityA,entity As
     * entityB Where
     * entityA.entityNameARePropertyName=entityB.entityNameBRePropertyName And
     * entityA.entityAWherePropertyName1=entityAWherePropertyValue1 And
     * entityA.entityAWherePropertyName2 In (entityAWherePropertyValues2)
     *
     * @param <T>                         实体所属的类型
     * @param clazz                       实体所属的类
     * @param entityNameARePropertyName   进行自关联的属性名
     * @param entityNameBRePropertyName   进行自关联的属性名
     * @param entityAWherePropertyName1   entityB条件属性名
     * @param entityAWherePropertyValue1  entityB条件属性值列表
     * @param entityAWherePropertyName2   entityB条件属性名
     * @param entityAWherePropertyValues2 entityB条件属性值列表
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> List<T> listSelfRelation(Class<T> clazz,
                                                              String entityNameARePropertyName, String entityNameBRePropertyName,
                                                              String entityAWherePropertyName1,
                                                              Object entityAWherePropertyValue1,
                                                              String entityAWherePropertyName2,
                                                              Collection<?> entityAWherePropertyValues2) {
        List<T> entityList = new ArrayList<T>();

        String entityNameA = EntityUtil.getEntityNameAppendA(clazz);
        String entityNameB = EntityUtil.getEntityNameAppendB(clazz);

        StringBuffer JPQL = JPQLUtil.selectEntity(entityNameB);
        JPQL.append(JPQLUtil.fromTowEntities(clazz));
        JPQL.append(JPQLUtil.whereIdentity());
        if (StringUtils.isNotBlank(entityNameARePropertyName)
                && StringUtils.isNotBlank(entityNameBRePropertyName)) {
            JPQL.append(JPQLUtil.andTwoEntityRelation(entityNameA,
                    entityNameARePropertyName, entityNameB,
                    entityNameBRePropertyName));
        }
        List<Object> conditionValues = new ArrayList<Object>();
        if (StringUtils.isNotBlank(entityAWherePropertyName1)
                && entityAWherePropertyValue1 != null) {
            JPQL.append(JPQLUtil.andPropertyEqualQuestionSign(entityNameA,
                    entityAWherePropertyName1));
            conditionValues.add(entityAWherePropertyValue1);
        }
        if (StringUtils.isNotBlank(entityAWherePropertyName2)
                && CollectionUtils.isNotEmpty(entityAWherePropertyValues2)) {
            JPQL.append(JPQLUtil.andPropertyIn(entityNameA,
                    entityAWherePropertyName2, entityAWherePropertyValues2));
        }

        entityList = getRepository().createJpqlQuery(JPQL.toString())
                .setParameters(conditionValues).list();

        return entityList;
    }

    /**
     * 根据查询条件列出自关联的实体,JQPL语句形如: Select entityB From entity As entityA,entity As
     * entityB Where
     * entityA.entityNameARePropertyName=entityB.entityNameBRePropertyName And
     * entityA.entityAWherePropertyName1=entityAWherePropertyValue1
     *
     * @param <T>                       实体所属的类型
     * @param clazz                     实体所属的类
     * @param entityAWherePropertyName  entityB条件属性名
     * @param entityAWherePropertyValue entityB条件属性值列
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> List<T> listSelfRelation(Class<T> clazz,
                                                              String entityNameARePropertyName, String entityNameBRePropertyName,
                                                              String entityAWherePropertyName, Object entityAWherePropertyValue) {
        return listSelfRelation(clazz, entityNameARePropertyName,
                entityNameBRePropertyName, entityAWherePropertyName,
                entityAWherePropertyValue, null, null);
    }


2.1.2 使用示例

public static List<PhotoType> listSonPhotoTypes(String fatherPhotoTypeName) {
		List<PhotoType> photoTypes = new ArrayList<PhotoType>();
		if (StringUtils.isNotBlank(fatherPhotoTypeName)) {
			photoTypes = listSelfRelation(PhotoType.class, "id", "upid",
					"name", fatherPhotoTypeName);
		}
		return photoTypes;
	}


2.2 分页查询

2.2.1 对应方法

 /**
     * 分页查询实体
     *
     * @param <T>                 实体所属的类型
     * @param clazz               实体所属的类
     * @param wherePropertyName   条件属性名
     * @param wherePropertyValue  条件属性值
     * @param pageIndex           当前页
     * @param pageSize            每页显示的数据量
     * @param orderByPropertyName 进行排序的属性名,为null则不排序
     * @param isDESC              是否按倒序排列,为null或false按升序排序
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> Page<T> page(Class<T> clazz,
                                                  int pageIndex, int pageSize, String wherePropertyName,
                                                  Object wherePropertyValue, String orderByPropertyName,
                                                  Boolean isDESC) {
        return page(clazz, wherePropertyName, wherePropertyValue, null, null,
                pageIndex, pageSize, orderByPropertyName, isDESC);

    }

    /**
     * 分页查询实体
     *
     * @param <T>                 实体所属的类型
     * @param clazz               实体所属的类
     * @param wherePropertyName   条件属性名
     * @param wherePropertyValues 条件属性值列表
     * @param pageIndex           当前页
     * @param pageSize            每页显示的数据量
     * @param orderByPropertyName 进行排序的属性名,为null则不排序
     * @param isDESC              是否按倒序排列,为null或false按升序排序
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> Page<T> page(Class<T> clazz,
                                                  String wherePropertyName, Collection<?> wherePropertyValues,
                                                  int pageIndex, int pageSize, String orderByPropertyName,
                                                  Boolean isDESC) {
        Page<T> entityPage = new Page<T>(0, 0, pageSize, new ArrayList<T>());
        String entityName = EntityUtil.getEntityName(clazz);
        StringBuffer JPQL = JPQLUtil.selectByPropertyIn(entityName,
                wherePropertyName, wherePropertyValues);
        if (StringUtils.isNotBlank(JPQL)
                && CollectionUtils.isNotEmpty(wherePropertyValues)) {
            if (StringUtils.isNotBlank(orderByPropertyName)) {
                JPQL.append(JPQLUtil.orderBy(entityName, orderByPropertyName));
                if (isDESC != null && isDESC) {
                    JPQL.append(JPQLUtil.orderDESC());
                }
            }
            entityPage = getQueryChannelService()
                    .createJpqlQuery(JPQL.toString())
                    .setPage(pageIndex, pageSize).pagedList();
        }
        return entityPage;
    }

    /**
     * 分页查询实体
     *
     * @param <T>                  实体所属的类型
     * @param clazz                实体所属的类
     * @param wherePropertyName1   条件1属性名
     * @param wherePropertyValue1  条件1属性值列表
     * @param wherePropertyName2   条件2属性名
     * @param wherePropertyValues2 条件2属性值列表
     * @param pageIndex            当前页
     * @param pageSize             每页显示的数据量
     * @param orderByPropertyName  进行排序的属性名,为null则不排序
     * @param isDESC               是否按倒序排列,为null或false按升序排序
     * @return 符合条件的实体列表
     */
    public static <T extends Entity> Page<T> page(Class<T> clazz,
                                                  String wherePropertyName1, Object wherePropertyValue1,
                                                  String wherePropertyName2, Collection<?> wherePropertyValues2,
                                                  int pageIndex, int pageSize, String orderByPropertyName,
                                                  Boolean isDESC) {
        Page<T> entityPage = new Page<T>(0, 0, pageSize, new ArrayList<T>());
        String entityName = EntityUtil.getEntityName(clazz);
        StringBuffer JPQL = JPQLUtil.selectEntity(entityName);
        JPQL.append(JPQLUtil.fromEntity(entityName));
        JPQL.append(JPQLUtil.whereIdentity());
        List<Object> conditionValues = new ArrayList<Object>();
        if (StringUtils.isNotBlank(wherePropertyName1)
                && wherePropertyValue1 != null) {
            JPQL.append(JPQLUtil.andPropertyEqualQuestionSign(entityName,
                    wherePropertyName1));
            conditionValues.add(wherePropertyValue1);
        }
        if (StringUtils.isNotBlank(wherePropertyName2)
                && CollectionUtils.isNotEmpty(wherePropertyValues2)) {
            JPQL.append(JPQLUtil.andPropertyIn(entityName, wherePropertyName2,
                    wherePropertyValues2));
        }

        if (StringUtils.isNotBlank(orderByPropertyName)) {
            JPQL.append(JPQLUtil.orderBy(entityName, orderByPropertyName));
            if (isDESC != null && isDESC) {
                JPQL.append(JPQLUtil.orderDESC());
            }
        }
        entityPage = getQueryChannelService().createJpqlQuery(JPQL.toString())
                .setParameters(conditionValues).setPage(pageIndex, pageSize)
                .pagedList();
        return entityPage;
    }

2.2.2 使用示例

 @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Page<PhotoCollectionDTO> page(int pageIndex, int pageSize,
                                         String type, String orderByPropertyName, Boolean isDESC)
            throws Exception {
        Page<PhotoCollectionDTO> photoCollectionDTOPage = new Page<PhotoCollectionDTO>(
                0, 0, pageSize, new ArrayList<PhotoCollectionDTO>());
        Page<PhotoCollection> photoCollectionPage = PhotoCollection.page(
                PhotoCollection.class, pageIndex, pageSize, "type", type,
                orderByPropertyName, isDESC);
        List<PhotoCollection> photoCollections = photoCollectionPage.getData();
        if (photoCollectionPage != null && photoCollections.size() > 0) {

            List<String> photographerNameList = PhotoCollection
                    .getCreatorList(photoCollections);

            Map<String, UserDetail> userNameAndUserDetailMap = UserDetail
                    .getUserNameAndSelfMap(photographerNameList);

            List<PhotoCollectionDTO> photoCollectionDTOs = new ArrayList<PhotoCollectionDTO>();

            for (PhotoCollection photoCollection : photoCollections) {
                PhotoCollectionDTO photoCollectionDTO = new PhotoCollectionDTO();
                BeanUtils.copyProperties(photoCollectionDTO, photoCollection);
                UserDetail userDetail = userNameAndUserDetailMap
                        .get(photoCollection.getCreator());
                if (userDetail != null) {
                    photoCollectionDTO.setPhotographerNickName(userDetail
                            .getNickName());
                    photoCollectionDTO.setPhotographerAvatarPath(userDetail
                            .getPhotoPath());
                }
                photoCollectionDTOs.add(photoCollectionDTO);
            }

            photoCollectionDTOPage = new Page<PhotoCollectionDTO>(
                    photoCollectionPage.getStart(),
                    photoCollectionPage.getResultCount(), pageSize,
                    photoCollectionDTOs);
        }

        return photoCollectionDTOPage;
    }


你可能感兴趣的:(扩展Koala的KoalaLegacyEntity,增强其CRUD方面的功能——持续更新中)