使用spring-boot的jpa制作框架并实现自动生成功能

spring-boot集成jpa制作框架并自动生成代码

前言:

jpa的使用可以采用jpa接口规范或采用entityManger但用起来感觉不是很爽,以前用过mybatisplugin感觉很好用

现在就按照他的思想做了个


core核心层

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 *create by yinchong
 * @param  实体类
 */
public interface BaseDao {

    void save(T bean);

    void update(T bean);

    T findOne(Serializable id);

    /**
     * 根据id删除制定数据
     * @param id
     * @return
     */
    int delete(Serializable id);

    /**
     * 查询所有数据
     * @return
     */
    List findAll();

    /**
     * 分页显示数据
     * @param pageNum
     * @param pageSize
     * @return
     */
    List pageList(int pageNum, int pageSize);

    /**
     * 查询所有并按主键降序
     * @return
     */
    List findAllDesc();

    /**
     * 分页显示并按主键降序
     * @return
     */
    List pageListDesc(int pageNum, int pageSize);

    /**
     * 对指定字段降序排序
     * @param fieldName
     * @return
     */
    List findAllDesc(String fieldName);

    /**
     * 安某个字段并查找指定数据个数
     * @param fielName
     * @param pageNum
     * @param pageSize
     * @return
     */
    List pageListDesc(String fielName, int pageNum, int pageSize);

    /**
     * 查询所有并按主键升序
     * @return
     */
    List findAllAsc();

    /**
     * 查找指定数量并按主键升序
     * @param pageNum
     * @param pageSize
     * @return
     */
    List pageListAsc(int pageNum, int pageSize);

    /**
     * 对指定字段升序排序
     * @param fieldName
     * @return
     */
    List findAllAsc(String fieldName);

    /**
     * 对指定字段降序并查询指定数量
     * @param fieldName
     * @param pageNum
     * @param pageSize
     * @return
     */
    List pageListAsc(String fieldName, int pageNum, int pageSize);

    /**
     * 批量保存
     * @param beans
     */
    void batchSave(List beans);

    /**
     * 批量更新所有字段
     * @param beans
     */
    void batchUpdate(List beans);

    /**
     * 批量删除
     * @param ids
     * @return
     */
     int batchDelete(List ids);

    /**
     * 批量更新非空字段
     * @param beans
     */
    void batchUpdateNotNull(List beans);

    /**
     * 这个用于执行删除和更新的sql语句
     *
     * @param sql
     * @param params
     */
    int executeSql(String sql, Object... params);

    /**
     * 这个用于执行删除和更新的hql语句
     * @param hql
     * @param params
     */
    int executeHql(String hql, Object... params);

    /**
     * 根据原始sql语句执行sql
     *
     * @param sql    原始sql语句
     * @param params 要传递的参数
     * @return map对象
     */
    List> findSql(String sql, Object... params);

    /**
     * @param sql    原始sql语句
     * @param clazz  要反射的Class对象
     * @param params 要传递的参数
     * @param 
     * @return
     */
     List findSql(String sql, Class clazz, Object... params);

    /**
     * 执行原始sql并返回Object[]集合
     * @param sql
     * @param params
     * @return
     */
    List findObjectSql(String sql, Object... params);

    /**
     * 分页显示数据
     *
     * @param sql
     * @param pageNum  第几页
     * @param pageSize 每页显示多少个
     * @param params   需要传递的参数
     * @return
     */
    PageBean> pageSql(String sql, Integer pageNum, Integer pageSize, Object... params);

    /**
     * 分页查询
     * @param sql
     * @param pageNum
     * @param pageSize
     * @param params
     * @return
     */
    PageBean pageObjectSql(String sql,int pageNum,int pageSize,Object ...params);

    /**
     * 执行hql查询语句
     * @param hql
     * @param params
     * @return
     */
    List findHql(String hql, Object... params);

    /**
     * hql语句返回Object[]对象
     * @param hql
     * @param params
     * @return
     */
    List findObjectHql(String hql, Object... params);

    /**
     * hql的分页操作
     * @param hql
     * @param pageNum
     * @param pageSize
     * @param params
     * @return
     */
    PageBean pageHql(String hql, Integer pageNum, Integer pageSize, Object... params);


    /**
     *hql执行统计总数
     * @param hql
     * @param params
     * @return
     */
    Long countHql(String hql, Object... params);

    /**
     * 执行统计总数
     * @param sql
     * @param params
     * @return
     */
    Long countSql(String sql, Object... params);

    /**
     * 更新非空字段
     * @param bean
     * @return
     */
    int updateNotNull(T bean);

    /**
     * 根据字段删除数据
     * @param field
     * @param value
     * @return
     */
    int deleteEqualField(String field, Object value);

    /**
     * like匹配删除
     * @param field
     * @param value
     * @return
     */
    int deleteLikeField(String field, String value);

    /**
     * 相等查找
     * @param field 字段名
     * @param value 字段对应的值
     * @return
     */
    List findEqualField(String field, Object value);

    /**
     * like匹配查找
     * @param field 字段名
     * @param value 字段对应的值
     * @return
     */
    List findLikeField(String field, String value);

    /**
     * 根据字段进行between查询
     * @param field
     * @param start
     * @param end
     * @return
     */
    List findBetweenField(String field, Object start, Object end);

    /**
     * 删除所有
     */
    int deleteAll();

    /**
     * 对bean对象的多个字段and的equal匹配
     * @param data
     * @return
     */
    List findAndFields(Map data);

    /**
     * 对bean对象多个字段or的equal匹配
     * @param data
     * @return
     */
    List findOrFields(Map data);

    /**
     * 获取一个指定类型结果
     * @param hql
     * @param clazz
     * @param 
     * @return
     */
     T2 findOneHql(String hql, Class clazz, Object... params);

    /**
     * 获取一个指定类型结果
     * @param sql
     * @param clazz
     * @param 
     * @return
     */
     T2 findOneSql(String sql, Class clazz, Object... params);
}


import org.hibernate.transform.Transformers;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.math.BigInteger;
import java.util.*;

/***
**create by yinchong
*/
public class BaseDaoImpl implements BaseDao {

    private Class clazz;

    public BaseDaoImpl() {
        ParameterizedType t = (ParameterizedType) this.getClass().getGenericSuperclass();
        //获取泛型参数的实际类型
        this.clazz = (Class) t.getActualTypeArguments()[0];
    }

    @PersistenceContext
    protected EntityManager entityManager;


    @Transactional(propagation = Propagation.REQUIRED)
    public void save(T bean) {
       Field id =  ReflectUtils.getIdField(bean.getClass());
       Object value = null;
        try {
            value = id.get(bean);
        } catch (IllegalAccessException e) {
           throw new RuntimeException(e);
        }
        if(value==null) {
           entityManager.persist(bean);
       }else{
           update(bean);
       }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void update(T bean) {
        entityManager.merge(bean);
    }

    public T findOne(Serializable id) {
        return entityManager.find(clazz, id);
    }


    /**
     * @param id
     * @return 小于0 表示删除失败 大与0表示删除成功
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public int delete(Serializable id) {
        String hql = "delete from " + clazz.getSimpleName() + " p where p."+getIdProperties(clazz)+" = ?1";
        Query query = entityManager.createQuery(hql);
        query.setParameter(1, id);
        return query.executeUpdate();
    }

    private String getIdProperties(Class clazz){
       Field field =  ReflectUtils.getIdField(clazz);
       return field.getName();
    }


    /**
     * 显示所有数据
     * @return
     */
    public List findAll() {
        String hql = "select t from " + clazz.getSimpleName() + " t";
        Query query = entityManager.createQuery(hql,clazz);
        List beans = query.getResultList();
        return beans;
    }

    @Override
    public List pageList(int pageNum, int pageSize) {
        String hql = "select t from " + clazz.getSimpleName() + " t";
        Query query = entityManager.createQuery(hql,clazz);
        limitDatas(pageNum,pageSize,query);
        List beans = query.getResultList();
        return beans;
    }

    @Override
    public List findAllDesc() {
        String id = getIdProperties(clazz);
        String hql = "select t from " + clazz.getSimpleName() + " t order by t."+id+" desc";
        return findHql(hql);
    }

    @Override
    public List pageListDesc(int pageNum, int pageSize) {
        String id = getIdProperties(clazz);
        String hql = "select t from " + clazz.getSimpleName() + " t order by t."+id+" desc";
        Query query = entityManager.createQuery(hql,clazz);
        limitDatas(pageNum,pageSize,query);
        return query.getResultList();
    }

    @Override
    public List findAllDesc(String fieldName) {
        String hql = "select t from " + clazz.getSimpleName() + " t order by t."+fieldName+" desc";
        return findHql(hql);
    }

    @Override
    public List pageListDesc(String fieldName, int pageNum, int pageSize) {
        String hql = "select t from " + clazz.getSimpleName() + " t order by t."+fieldName+" desc";
        Query query = entityManager.createQuery(hql,clazz);
       limitDatas(pageNum,pageSize,query);
        return query.getResultList();
    }

    @Override
    public List findAllAsc() {
        String id = getIdProperties(clazz);
        String hql = "select t from " + clazz.getSimpleName() + " t order by t."+id+" asc";
        return findHql(hql);
    }

    @Override
    public List pageListAsc(int pageNum, int pageSize) {
        if(pageNum<=0)
            pageNum=1;
        String id = getIdProperties(clazz);
        String hql = "select t from " + clazz.getSimpleName() + " t order by t."+id+" asc";
        Query query = entityManager.createQuery(hql,clazz);
        query.setFirstResult((pageNum-1)*pageSize);
        query.setMaxResults(pageSize);
        return query.getResultList();
    }

    @Override
    public List findAllAsc(String fieldName) {
        String hql = "select t from " + clazz.getSimpleName() + " t order by t."+fieldName+" asc";
        return findHql(hql);
    }

    @Override
    public List pageListAsc(String fieldName, int pageNum, int pageSize) {
        if(pageNum<=0)
            pageNum=1;
        String hql = "select t from " + clazz.getSimpleName() + " t order by t."+fieldName+" asc";
        Query query = entityManager.createQuery(hql,clazz);
        query.setFirstResult((pageNum-1)*pageSize);
        query.setMaxResults(pageSize);
        return query.getResultList();
    }


    /**
     * 批量插入
     * @param beans
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void batchSave(List beans) {
        int count =0;
        if (beans != null) {
            for (T bean : beans) {
                count++;
                entityManager.persist(bean);
                if(count%1000==0){
                    entityManager.flush();
                    entityManager.clear();
                }
            }
            entityManager.flush();
            entityManager.clear();
        }

    }


    /**
     * 批量更新
     * @param beans
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void batchUpdate(List beans) {
        if (beans != null) {
            for (T bean : beans)
                entityManager.merge(bean);
            entityManager.flush();
            entityManager.clear();
        }
    }


    @Transactional(propagation = Propagation.REQUIRED)
    public int batchDelete(List ids) {
        StringBuffer hql = new StringBuffer("delete from " + clazz.getSimpleName() + " p where p."+getIdProperties(clazz)+"  in(:ids)");
        Query query = entityManager.createQuery(hql.toString());
        query.setParameter("ids", ids);
        return query.executeUpdate();
    }


    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void batchUpdateNotNull(List beans) {
        if (beans == null || beans.size() == 0)
            return;
            List> datas = new LinkedList<>();
            for (T bean : beans) {
                Map data = ReflectUtils.createMapForNotNull(bean);
                datas.add(data);
            }
            String id = getIdProperties(clazz);

            for (Map map : datas) {
                //拼接Hql语句
                StringBuffer hql = new StringBuffer("update " + clazz.getSimpleName() + "");
                Set keys = map.keySet();
                boolean fist = true;
                for (String key : keys) {
                    if (key.equals(id))
                        continue;
                    if (fist) {
                        hql.append(" set ").append(key + "=:" + key);
                        fist = false;
                    } else {
                        hql.append("," + key + "=:" + key);
                    }
                }
                hql.append(" where "+id+"=:"+id);
                Query query = entityManager.createQuery(hql.toString());

                //设置参数
                for (String key : keys) {
                    Object value = map.get(key);
                    query.setParameter(key, value);
                }
                query.executeUpdate();
            }
            entityManager.flush();
            entityManager.clear();

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int executeSql(String sql, Object... params) {
        Query query = createSqlQuery(sql, params);
        return query.executeUpdate();
    }

    /**
     * 生成Query对象
     * @param sql
     * @param params
     * @return
     */
    private Query createSqlQuery(String sql, Object[] params) {
        Map map = getSql(sql);
        int count = (int) map.get("count");
        Query query = entityManager.createNativeQuery(sql);
        setQueryParameters(count,query,params);
        return query;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int executeHql(String hql, Object... params) {
        Query query = createHqlQuery(hql, params);
        return query.executeUpdate();
    }

    /**
     * 生成Hql可执行的query对象
     * @param hql
     * @param params
     * @return
     */
    private Query createHqlQuery(String hql, Object[] params) {
        Map map = getHSql(hql);
        String jpaHql = (String) map.get("sql");
        int count = (int) map.get("count");
        Query query = entityManager.createQuery(jpaHql);
        setQueryParameters(count,query,params);
        return query;
    }

    @Override
    public List> findSql(String sql, Object... params) {
        if(sql==null||sql.equals(""))
            return null;
        Map map = getHSql(sql);
        String jpaSql = (String) map.get("sql");
        Integer count = (Integer) map.get("count");
        Query query = entityManager.createNativeQuery(jpaSql);
        setQueryParameters(count,query,params);
        return query.unwrap(org.hibernate.SQLQuery.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
    }

    @Override
    public  List findSql(String sql, Class clazz, Object... params) {
        Map map = getSql(sql);
        String jpaSql = (String) map.get("sql");
        Integer count = (Integer) map.get("count");
        Query query = entityManager.createNativeQuery(jpaSql,clazz);
        setQueryParameters(count,query,params);
        return query.getResultList();
    }

    @Override
    public List findObjectSql(String sql, Object... params) {
        Map map = getSql(sql);
        String jpaSql = (String) map.get("sql");
        Integer count = (Integer) map.get("count");
        Query query = entityManager.createNativeQuery(jpaSql);
        setQueryParameters(count,query,params);
        return query.getResultList();
    }


    @Override
    public PageBean> pageSql(String sql, Integer pageNum, Integer pageSize, Object... params) {
        PageBean> pageBean = new PageBean<>();
        pageBean.setPageNum(pageNum);
        pageBean.setPageSize(pageSize);
        Map map = getSql(sql);
        String jpaSql = (String) map.get("sql");
        Integer count = (Integer) map.get("count");
        Long totalCount = getCount(sql, count, params);
        if(totalCount==null||totalCount==0){
            pageBean.setTotalCount(0L);
            return pageBean;
        }
        pageBean.setTotalCount(totalCount);
        Query query = entityManager.createNativeQuery(jpaSql);
        limitDatas(pageNum,pageSize,query);
        if (params != null && params.length > 0) {
            int length = params.length;
            for (int i = 0; i < length; i++) {
                query.setParameter(i + 1, params[i]);
            }
        }
        List> result =   query.unwrap(org.hibernate.SQLQuery.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        pageBean.setDatas(result);
        return pageBean;
    }

    private Long getCount(String sql, Integer count, Object... params) {
        if (params != null) {
            if (count != params.length)
                throw new RuntimeException("参数数量和?不一致");
        }
        int end = sql.lastIndexOf("order by");
        if(end<=0){
            end = sql.lastIndexOf("ORDER BY");
        }
        String tempSql = sql;
        if(end>0){
            tempSql = tempSql.substring(0,end);
        }
        tempSql ="select count(1) from (" +tempSql+") as temp";
        return countSql(tempSql,params);
    }

    @Override
    public PageBean pageObjectSql(String sql, int pageNum, int pageSize, Object... params) {
        PageBean pageBean = new PageBean<>();
        pageBean.setPageNum(pageNum);
        pageBean.setPageSize(pageSize);
        Map map = getSql(sql);
        String jpaSql = (String) map.get("sql");
        Integer count = (Integer) map.get("count");
        Long totalCount = getCount(sql, count, params);
        if(totalCount==null||totalCount==0){
            pageBean.setTotalCount(0L);
            return pageBean;
        }
        pageBean.setTotalCount(totalCount);
        Query query = entityManager.createNativeQuery(jpaSql);
        limitDatas(pageNum,pageSize,query);
        if (params != null && params.length > 0) {
            int length = params.length;
            for (int i = 0; i < length; i++) {
                query.setParameter(i + 1, params[i]);
            }
        }
        List datas =query.getResultList();
        pageBean.setDatas(datas);
        return pageBean;
    }

    private Map getSql(String sql) {
        sql += " ";
        int count = 0;
        Map map = new HashMap<>();
        map.put("sql", sql);
        map.put("count", count);
        String[] datas = sql.split("\\?");
        int length = datas.length;
        if (length == 1)
            return map;
        for (int i = 0; i < length - 1; i++) {
            count++;
        }
        map.put("count", count);
        return map;
    }

    private Map getHSql(String sql) {
        sql += " ";
        int count = 0;
        Map map = new HashMap<>();
        map.put("count", count);
        map.put("sql", sql);
        String[] datas = sql.split("\\?");
        int length = datas.length;
        if (length == 1)
            return map;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length - 1; i++) {
            count++;
            sb.append(datas[i]).append("?" + count).append(" ");
        }
        sb.append(datas[length-1]);
        map.put("count", count);
        map.put("sql", sb.toString());
        return map;
    }

    @Override
    public List findHql(String hql, Object... params) {
        Map map = getHSql(hql);
        String jpaSql = (String) map.get("sql");
        Integer count = (Integer) map.get("count");
        //获取数据
        Query query = entityManager.createQuery(jpaSql,clazz);
        setQueryParameters(count,query,params);
        List records =  query.getResultList();
        return records;
    }

    @Override
    public List findObjectHql(String hql, Object... params) {
        Map map = getHSql(hql);
        String jpaSql = (String) map.get("sql");
        Integer count = (Integer) map.get("count");
        //获取数据
        Query query = entityManager.createQuery(jpaSql);
        setQueryParameters(count,query,params);
        List records =  query.getResultList();
        return records;
    }

    @Override
    public PageBean pageHql(String hql, Integer pageNum, Integer pageSize, Object... params) {

        PageBean pageBean = new PageBean<>();
        pageBean.setPageNum(pageNum);
        pageBean.setPageSize(pageSize);
        Map map = getHSql(hql);
        String jpaSql = (String) map.get("sql");
        Integer count = (Integer) map.get("count");
        Long totalCount = getHCount(jpaSql, count, params);
        if(totalCount==null||totalCount==0){
            pageBean.setTotalCount(0L);
            return pageBean;
        }
        pageBean.setTotalCount(totalCount);

        //获取数据
        Query query = entityManager.createQuery(jpaSql,clazz);
        if (params != null && params.length > 0) {
            int length = params.length;
            for (int i = 0; i < length; i++) {
                query.setParameter(i + 1, params[i]);
            }
        }
        limitDatas(pageNum, pageSize, query);
        List records =  query.getResultList();
        pageBean.setDatas(records);
        return pageBean;
    }

    /**
     * 执行count操作
     * @param jpaSql
     * @param count
     * @param params
     * @return
     */
    private Long getHCount(String jpaSql, Integer count, Object... params) {
        if (params != null) {
            if (params.length != count) {
                throw new RuntimeException("sql 语句和参数数量不一致");
            }
        }
        //执行count操作
        boolean flag = jpaSql.startsWith("select");
        int end = jpaSql.lastIndexOf("order by");
        if(end<=0){
            end = jpaSql.lastIndexOf("ORDER BY");
        }
        String tempHql =jpaSql;
        if(flag) {
            if (end > 0) {
                tempHql = tempHql.substring(0, end);
            }
            tempHql= "select count(1) from("+tempHql+") as temp";
        }else{
            tempHql="select count(1) "+tempHql;
        }

        return countHql(tempHql,params);
    }

    /**
     * 数据分页
     * @param pageNum
     * @param pageSize
     * @param query
     */
    private void limitDatas(Integer pageNum, Integer pageSize, Query query) {
        if(pageNum!=null&&pageSize!=null){
            if(pageNum<=0)
                pageNum=1;
            query.setFirstResult((pageNum-1)*pageSize);
            query.setMaxResults(pageSize);
        }
    }

    @Override
    public Long countHql(String hql, Object... params) {
        Query query = createHqlQuery(hql,params);
        return ((Long)query.getSingleResult());
    }

    /**
     * 为Query设置参数
     * @param count
     * @param query
     * @param params
     */
    private void setQueryParameters(Integer count, Query query, Object[] params) {
        if (params != null) {
            if (params.length != count) {
                throw new RuntimeException("sql 语句和参数数量不一致");
            }
            int length = params.length;
            for (int i = 0; i < length; i++) {
                query.setParameter(i + 1, params[i]);
            }
        }
    }

    @Override
    public Long countSql(String sql, Object... params) {
        Query query =createSqlQuery(sql,params);
        return ((BigInteger) query.getSingleResult()).longValue();
    }

    @Override
    public int updateNotNull(T bean) {
        try {
            batchUpdateNotNull(Arrays.asList(bean));
        }catch (Exception e){
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>:error:"+e.getMessage()+""+e.getCause());
            return -1;
        }
         return 1;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int deleteEqualField(String field, Object value) {
        Query query = entityManager.createQuery("delete from " + clazz.getSimpleName() + " p where p."+field+" = ?1");
        query.setParameter(1, value);
        return query.executeUpdate();
    }


    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int deleteLikeField(String field,String value){
        Query query = entityManager.createQuery("delete from " + clazz.getSimpleName() + " p where p."+field+" like ?1");
        query.setParameter(1, value);
        return query.executeUpdate();
    }

    @Override
    public List findEqualField(String field, Object value) {
        Query query = entityManager.createQuery("select p from "+clazz.getSimpleName()+" p where p."+field+" = ?1",clazz);
        query.setParameter(1,value);
        List records =  query.getResultList();
        return records;
    }

    @Override
    public List findLikeField(String field, String value) {
        Query query = entityManager.createQuery("select p from "+clazz.getSimpleName()+" p where p."+field+" like ?1");
        query.setParameter(1,value);
        List records =  query.getResultList();
        return records;
    }

    @Override
    public List findBetweenField(String field, Object start, Object end) {
        Query query = entityManager.createQuery("select p from "+clazz.getSimpleName()+" p where p."+field+" between ?1 and ?2");
        query.setParameter(1,start);
        query.setParameter(2,end);
        List records =  query.getResultList();
        return records;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int deleteAll() {
        Query query = entityManager.createQuery("delete from " + clazz.getSimpleName() + " p ");
        return query.executeUpdate();
    }

    @Override
    public List findAndFields(Map data) {
        StringBuilder sb = new StringBuilder("select p from "+clazz.getSimpleName()+" p ");
        if(data!=null){
            boolean flag = true;
           for(String key:data.keySet()){
               if(flag){
                   sb.append(" where ").append(key).append(" =:").append(key);
                   flag = false;
               }else{
                   sb.append(" and ").append(key).append(" =:").append(key);
               }
           }
        }
      Query query =  entityManager.createQuery(sb.toString());
        setQueryParamters(data, query);
        return query.getResultList();
    }

    @Override
    public List findOrFields(Map data) {
        StringBuilder sb = new StringBuilder("select p from "+clazz.getSimpleName()+" p ");
        if(data!=null){
            boolean flag = true;
            for(String key:data.keySet()){
                if(flag){
                    sb.append(" where ").append(key).append(" =:").append(key);
                    flag = false;
                }else{
                    sb.append(" or ").append(key).append(" =:").append(key);
                }
            }
        }
        Query query =  entityManager.createQuery(sb.toString());
        setQueryParamters(data, query);
        return query.getResultList();
    }

    @Override
    public  T2 findOneHql(String hql, Class clazz,Object... params) {
        Map map = getHSql(hql);
        String jpaSql = (String) map.get("sql");
        Integer count = (Integer) map.get("count");
        //获取数据
        Query query = entityManager.createQuery(jpaSql,clazz);
        setQueryParameters(count,query,params);
        return (T2) query.getResultList();
    }

    @Override
    public  T2 findOneSql(String sql, Class clazz,Object... params) {
        Map map = getSql(sql);
        String jpaSql = (String) map.get("sql");
        Integer count = (Integer) map.get("count");
        Query query = entityManager.createNativeQuery(jpaSql,clazz);
        setQueryParameters(count,query,params);
        return (T2) query.getResultList();
    }

    private void setQueryParamters(Map data, Query query) {
        if(data!=null){
            for(Map.Entry entry:data.entrySet()){
                String key = entry.getKey();
                Object value = entry.getValue();
                query.setParameter(key,value);
            }
        }
    }


}


import java.io.Serializable;
import java.util.List;

/**
 * 基础service
 */
public interface IService {
    /**
     * 保存
     * @param bean
     * @return
     */
    int save(T bean);

    /**
     * 更新
     * @param bean
     * @return
     */
    int update(T bean);

    /**
     * 删除
     * @param id
     * @return
     */
    int delete(Serializable id);

    /**
     * 批量删除
     * @param ids
     */
    void batchDelete(List ids);

    /**
     * 批量添加
     * @param datas
     */
    void batchAdd(List datas);

    /**
     * 批量更新
     * @param datas
     */
    void batchUpdate(List datas);

    /**
     * 显示所有
     * @return
     */
    List listAll();

    /**
     * 根据字段查找
     * @param fieldName
     * @param value
     * @return
     */
    List listEqualField(String fieldName, Object value);

    /**
     * 根据字段模糊查找
     * @param fieldName
     * @param value
     * @return
     */
    List listLikeField(String fieldName, String value);

    /**
     * 根据字段范围查找
     * @param fieldName
     * @param start
     * @param end
     * @return
     */
    List listBetweenField(String fieldName, Object start, Object end);

}


import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;

public class ServiceImpl,T> implements IService{

    @Autowired
    protected M  baseDao;

    @Override
    public int save(T bean) {
        try {
            baseDao.save(bean);
            return 1;
        }catch (Exception e) {
            return -1;
        }
    }

    @Override
    public int update(T bean) {
        try {
            baseDao.update(bean);
            return 1;
        }catch (Exception e) {
            return -1;
        }
    }

    @Override
    public int delete(Serializable id) {
        return baseDao.delete(id);
    }

    @Override
    public void batchDelete(List ids) {
         baseDao.batchDelete(ids);
    }

    @Override
    public void batchAdd(List datas) {
        baseDao.batchSave(datas);
    }

    @Override
    public void batchUpdate(List datas) {
          baseDao.batchUpdate(datas);
    }

    @Override
    public List listAll() {
        return baseDao.findAll();
    }

    @Override
    public List listEqualField(String fieldName, Object value) {
        return baseDao.findEqualField(fieldName,value);
    }

    @Override
    public List listLikeField(String fieldName, String value) {
        return baseDao.findLikeField(fieldName,value);
    }

    @Override
    public List listBetweenField(String fieldName, Object start, Object end) {
        return baseDao.findBetweenField(fieldName,start,end);
    }
}



import java.io.Serializable;
import java.util.List;

/**
 * 分页对象
 */
public class PageBean implements Serializable {
    //总共的数据条数
    private Long totalCount;
    //第几页
    private Integer pageNum;
    //每页显示多少
    private Integer pageSize;
    //查询出来的数据
    private List datas;

    public Long getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(Long totalCount) {
        this.totalCount = totalCount;
    }

    public Integer getPageNum() {
        return pageNum;
    }

    public void setPageNum(Integer pageNum) {
        this.pageNum = pageNum;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public List getDatas() {
        return datas;
    }

    public void setDatas(List datas) {
        this.datas = datas;
    }
}



import javax.persistence.Id;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 反射工具类
 * create by yinchong
 */
public abstract class ReflectUtils {

    //缓存类的字段
    private static Map> cache = new ConcurrentHashMap<>();

    //缓存类中id字段
    private static Map idsCache = new ConcurrentHashMap<>();

    public static Map createMapForNotNull(Object bean){
        List fields = listAllFields(bean.getClass());
        try {
            Map map = new HashMap<>();
            if (fields != null) {
                for (Field field : fields) {
                    Object value = field.get(bean);
                    if(value!=null){
                        String name = field.getName();
                        map.put(name,value);
                    }
                }
            }
            return map;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 通过反射获取制定的字段值
     * @param object
     * @param fieldName
     * @return
     */
    public static Object getFiledValue(Object object,String fieldName){
        Class clazz = object.getClass();
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.get(object);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取id注解的字段
     * @param clazz
     * @return
     */
    public static Field getIdField(Class clazz){
        String className = clazz.getName();
        Field field = idsCache.get(className);
        if(field!=null){
            return field;
        }
         List fields = listAllFields(clazz);
         if(fields==null){
             return null;
         }
         for(Field temp:fields){
             Id id = temp.getAnnotation(Id.class);
             if(id!=null){
                 idsCache.put(className,temp);
                 return temp;
             }
         }
         return null;
    }



    /**
     * 浅层次将对象转变为map
     * @param bean
     * @return
     */
    public static Map simpleReflectBeanToMap(Object bean)throws Exception{
        List fields = listAllFields(bean.getClass());
        if (fields == null || fields.size() == 0)
            return null;
        Map map = new HashMap<>();
        for (Field field : fields) {
            String name = field.getName();
            Object value = field.get(bean);
            if (isEmpty(value))
                continue;
            map.put(name, value);
        }
        return map;
    }

    /**
     * 深层次将对象转变为Map递归下去
     *
     * @param bean
     * @return
     * @throws Exception
     */
    public static Map reflectBeanToMap(Object bean) throws Exception {
        List fields = listAllFields(bean.getClass());
        if (fields == null || fields.size() == 0)
            return null;
        Map map = new HashMap<>();
        for (Field field : fields) {
            String name = field.getName();
            Object value = field.get(bean);
            if (isEmpty(value))
                continue;
            if (isSimpleType(field.getType())) {// 如果为基本类型
                map.put(name, value);
            } else {
                Map tempMap = reflectBeanToMap(value);
                map.put(name, tempMap);
            }
        }
        return map;
    }

    /**
     * 是否为null1
     *
     * @param value
     * @return
     */
    public static boolean isEmpty(Object value) {
        return value == null;
    }

    /**
     * 是否为基本类型
     *
     * @param clazz
     * @return
     */
    public static boolean isSimpleType(Class clazz) {
        if (clazz.equals(int.class) || clazz.equals(Integer.class))
            return true;
        if (clazz.equals(String.class))
            return true;
        if (clazz.equals(long.class) || clazz.equals(Long.class))
            return true;
        if (clazz.equals(float.class) || clazz.equals(Float.class))
            return true;
        if (clazz.equals(double.class) || clazz.equals(Double.class))
            return true;
        if (clazz.equals(short.class) || clazz.equals(Short.class))
            return true;
        if (clazz.equals(char.class) || clazz.equals(Character.class))
            return true;
        if (clazz.equals(boolean.class) || clazz.equals(Boolean.class))
            return true;
        return clazz.equals(byte.class) || clazz.equals(Byte.class);

    }

    /**
     * 列出该类及其子类下面所以得非静态字段
     *
     * @param clazz
     * @return
     */
    public static List listAllFields(Class clazz) {
        List result = cache.get(clazz.getName());
        if(result!=null)
            return result;
        Field[] fields = clazz.getDeclaredFields();
        if (fields == null || fields.length == 0)
            return null;
        result = new LinkedList<>();
        for (Field field : fields) {
            if (Modifier.isStatic(field.getModifiers()))
                continue;
            field.setAccessible(true);
            result.add(field);
        }
        if (clazz.getSuperclass() != null) {
            List temps = listAllFields(clazz.getSuperclass());
            if(temps!=null)
                result.addAll(temps);
        }
        cache.put(clazz.getName(), result);
        return result;
    }

    /**
     * 将简单的map映射成bean对象
     * @param data
     * @param clazz
     * @return
     * @throws Exception
     */
    public static  T simpleChangeMapToBean(Map data,Class clazz)throws Exception{
        List fields = listAllFields(clazz);
        T bean = (T) clazz.newInstance();
        if(fields!=null&&fields.size()>0){
            for(Field field:fields){
                String name = field.getName();
                Object value = data.get(name);
                if(isEmpty(value))
                    continue;
                field.set(bean, value);
            }
        }
        return bean;
    }

    /**
     * 深层次将map中的数据映射到bean中递归下去
     * @param data
     * @param clazz
     * @return
     * @throws Exception
     */
    public static  T changeMapToBean(Map data,Class clazz)throws Exception{
        List fields = listAllFields(clazz);
        T bean = (T) clazz.newInstance();
        if(fields!=null&&fields.size()>0){
            for(Field field:fields){
                String name = field.getName();
                Object value = data.get(name);
                if(isEmpty(value))
                    continue;
                if(isSimpleType(field.getType())){
                    field.set(bean, value);
                }else{
                    Map tempMap = (Map) value;
                    Object resultValue = changeMapToBean(tempMap,field.getType());
                    field.set(bean, resultValue);
                }
            }
        }
        return bean;
    }

    /**
     * 经对象上非静态熟悉映射到另一个对象属性上去
     * @param from 从哪个对象开始
     * @param to  到哪个对象
     */
    public static void reflectBean2Bean(Object from,Object to){
        Class fromClazz = from.getClass();
        Class toClazz = to.getClass();
       List fromFields =  listAllFields(fromClazz);
       List toFields = listAllFields(toClazz);

       try {
           if (fromFields != null && fromFields.size() != 0) {
               for (Field fromField : fromFields) {
                   Field toField = getFieldByNameAndTypeSame(toFields, fromField);
                   if (toField!=null) {
                       Object value = fromField.get(from);
                       toField.set(to,value);
                   }
               }
           }
       }catch (Exception e){
           throw new RuntimeException(e);
       }
    }


    private static Field getFieldByNameAndTypeSame(List datas,Field field){
        if(datas==null||datas.size()==0)
            return null;
        String name = field.getName();
        Class type = field.getType();
        for(Field data:datas){
            if(!data.getName().equals(name))
                continue;
            if(!data.getType().equals(type))
                continue;
            return data;
        }
        return null;
    }

}



=================================下面是自动生成service,dao,controller层代码=============


import java.io.File;
import java.util.List;

public class ControllerBuilder {

    private CoreConfig coreConfig;
    private String controllerPage;

    public ControllerBuilder(CoreConfig config){
        coreConfig = config;
        if(coreConfig.getControllerPage()!=null){
            controllerPage = coreConfig.getControllerPage();
        }else{
            controllerPage = coreConfig.getParentPacke()+".web";
        }
    }

    public void create(){
        List classNames = coreConfig.lisAllClassName();
        if(classNames!=null){
            for(String className:classNames){
                String controllerPath =  coreConfig.getControllerRealPath();
                String controllerName = className+"Controller";
                File path = new File(controllerPath);
                if(!path.exists()) {
                    path.mkdirs();
                }
                File file = new File(controllerPath+"//"+controllerName+".java");
                if(file.exists())
                    continue;
                StringBuilder sb = new StringBuilder("package "+controllerPage+";").append(PathConfig.newLine())//
                        .append("import "+coreConfig.getDomainPage()+"."+className+";").append(PathConfig.newLine())//
                        .append("import org.springframework.web.bind.annotation.RequestMapping;").append(PathConfig.newLine())//
                        .append("import org.springframework.web.bind.annotation.ResponseBody;").append(PathConfig.newLine())//
                        .append("import org.springframework.stereotype.Controller;").append(PathConfig.newLine())//
                        .append("@Controller").append(PathConfig.newLine())//
                        .append("@RequestMapping(\""+className+"\")").append(PathConfig.newLine())//
                        .append("public class "+controllerName+"{").append(PathConfig.newLine())//
                        .append(PathConfig.newLine())//
                        .append("\t@RequestMapping(\"test\")").append(PathConfig.newLine())//
                        .append("\t@ResponseBody").append(PathConfig.newLine())//
                        .append("\tpublic Object test(){").append(PathConfig.newLine())//
                        .append("\t\treturn \"success\";").append(PathConfig.newLine())//
                        .append("\t}").append(PathConfig.newLine())//
                        .append("}");// ;
                PathConfig.copyToFile(file,sb.toString());

                System.out.println(">>>>>>>>>>>>>>>>>>>>>>生成 "+controllerName+" 完成");
            }
        }
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>web层代码生成完成>>>>>>>>>>>>>>>>>>>");
    }
}

import java.io.File;
import java.util.List;

public class DaoBuilder {
    private CoreConfig coreConfig;
    private String daoPage;

    public DaoBuilder(CoreConfig config){
        coreConfig = config;
        if(coreConfig.getDaoPage()!=null){
            this.daoPage = coreConfig.getDaoPage();
        }else{
            daoPage = coreConfig.getParentPacke()+".dao";
        }
    }

    public void create(){
        List classNames = coreConfig.lisAllClassName();
        if(classNames!=null){
            for(String className:classNames){
               String daoPath =  coreConfig.getDaoRealPath();
               String daoName = className+"Dao";
               File path = new File(daoPath);
               File path2 = new File(daoPath+"//impl");
               if(!path.exists()) {
                   path.mkdirs();
                   path2.mkdirs();
               }
               File file = new File(daoPath+"//"+daoName+".java");
               if(file.exists())
                   continue;
               StringBuilder sb = new StringBuilder("package "+daoPage+";").append(PathConfig.newLine())//
                       .append("import "+coreConfig.getCorePage()+".*;").append(PathConfig.newLine())//
                       .append("import "+coreConfig.getDomainPage()+"."+className+";").append(PathConfig.newLine())//
                       .append("public interface "+daoName+" extends BaseDao<"+className+">{").append(PathConfig.newLine())//
                       .append("}");// ;
                PathConfig.copyToFile(file,sb.toString());
                //添加dao中内容
                String daoImplPath = daoPath+"//impl";
                String daoImplName = className+"DaoImpl";
                file = new File(daoImplPath+"//"+daoImplName+".java");
               sb = new StringBuilder("package "+daoPage+".impl;").append(PathConfig.newLine())//
                .append("import "+coreConfig.getCorePage()+".*;").append(PathConfig.newLine())//
                .append("import "+coreConfig.getDomainPage()+"."+className+";").append(PathConfig.newLine())//
                .append("import org.springframework.stereotype.Repository;").append(PathConfig.newLine())//
                 .append("import "+daoPage+"."+daoName+";")    .append(PathConfig.newLine())//
                .append("@Repository").append(PathConfig.newLine())//
                .append("public class "+daoImplName+" extends BaseDaoImpl<"+className+"> implements "+daoName+"{").append(PathConfig.newLine())//
                .append("}");
               PathConfig.copyToFile(file,sb.toString());
                System.out.println(">>>>>>>>>>>>>>>>>>>>>>生成 "+daoImplName+" 完成");
            }
        }
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>dao层代码生成完成>>>>>>>>>>>>>>>>>>>");
    }
}

import java.io.File;
import java.util.List;

public class ServiceBuilder {
    private CoreConfig coreConfig;
    private String servicePage;

    public ServiceBuilder(CoreConfig config){
        coreConfig = config;
        if(config.getServicePage()!=null){
            servicePage = config.getServicePage();
        }else{
            servicePage = config.getParentPacke()+".service";
        }
    }

    public void create(){
        List classNames = coreConfig.lisAllClassName();
        if(classNames!=null){
            for(String className:classNames){
                String servicePath =  coreConfig.getServiceRealPath();
                String serviceName = "I"+className+"Service";
                File path = new File(servicePath);
                File path2 = new File(servicePath+"//impl");
                if(!path.exists()) {
                    path.mkdirs();
                    path2.mkdirs();
                }
                File file = new File(servicePath+"//"+serviceName+".java");
                if(file.exists())
                    continue;
                StringBuilder sb = new StringBuilder("package "+servicePage+";").append(PathConfig.newLine())//
                        .append("import "+coreConfig.getCorePage()+".*;").append(PathConfig.newLine())//
                        .append("import "+coreConfig.getDomainPage()+"."+className+";").append(PathConfig.newLine())//
                        .append("public interface "+serviceName+" extends IService<"+className+">{").append(PathConfig.newLine())//
                        .append("}");// ;
                PathConfig.copyToFile(file,sb.toString());
                //添加dao中内容
                String serviceImplPath = servicePath+"//impl";
                String serviceImplName = className+"ServiceImpl";
                file = new File(serviceImplPath+"//"+serviceImplName+".java");
                sb = new StringBuilder("package "+servicePage+".impl;").append(PathConfig.newLine())//
                        .append("import "+coreConfig.getCorePage()+".*;").append(PathConfig.newLine())//
                        .append("import "+coreConfig.getDomainPage()+"."+className+";").append(PathConfig.newLine())//
                        .append("import "+coreConfig.getDaoPage()+"."+className+"Dao;").append(PathConfig.newLine())//
                        .append("import org.springframework.stereotype.Service;").append(PathConfig.newLine())//
                        .append("import "+servicePage+"."+serviceName+";").append(PathConfig.newLine())//
                        .append("@Service").append(PathConfig.newLine())//
                        .append("public class "+serviceImplName+" extends ServiceImpl<"+className+"Dao,"+className+"> implements "+serviceName+"{").append(PathConfig.newLine())//
                        .append("}");
                PathConfig.copyToFile(file,sb.toString());
                System.out.println(">>>>>>>>>>>>>>>>>>>>>>生成 "+serviceImplName+" 完成");
            }
        }
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>service层代码生成完成>>>>>>>>>>>>>>>>>>>");
    }

}


import java.util.LinkedList;
import java.util.List;

/**
 * 核心数据结构
 */
public class CoreConfig {
    //父路径
    private String parentPacke;
    //service接口包路径
    private String servicePage;
    //dao接口包路径
    private String daoPage;
    //controller接口包路径
    private String controllerPage;
    //实体类包路径
    private String domainPage;
    //核心工具类路径
    private String corePage;

    //存放类名称的数据
    private List classNames= new LinkedList<>();

    private String javaShortPath;

    private boolean openController =false;
    private boolean openService = true;
    private boolean openDao = true;

    public void addClassName(String className){
        classNames.add(className);
    }

    public List lisAllClassName(){
        return classNames;
    }

    public String getParentPacke() {
        return parentPacke;
    }

    public String getJavaShortPath() {
        return javaShortPath;
    }

    public void setJavaShortPath(String javaShortPath) {
        this.javaShortPath = javaShortPath;
    }

    public void setParentPacke(String parentPacke) {
        this.parentPacke = parentPacke;
    }

    public String getServicePage() {
        return servicePage;
    }

    public void setServicePage(String servicePage) {
        this.servicePage = servicePage;
    }

    public String getDaoPage() {
        return daoPage;
    }

    public void setDaoPage(String daoPage) {
        this.daoPage = daoPage;
    }

    public String getControllerPage() {
        return controllerPage;
    }

    public void setControllerPage(String controllerPage) {
        this.controllerPage = controllerPage;
    }

    public String getDomainPage() {
        return domainPage;
    }

    public void setDomainPage(String domainPage) {
        this.domainPage = domainPage;
    }

    public String getCorePage() {
        return corePage;
    }

    public void setCorePage(String corePage) {
        this.corePage = corePage;
    }

    public boolean isOpenController() {
        return openController;
    }

    public void setOpenController(boolean openController) {
        this.openController = openController;
    }

    public boolean isOpenService() {
        return openService;
    }

    public void setOpenService(boolean openService) {
        this.openService = openService;
    }

    public boolean isOpenDao() {
        return openDao;
    }

    public void setOpenDao(boolean openDao) {
        this.openDao = openDao;
    }

    public String getDomainRealPath(){
        String path = PathConfig.getProjectPath()+"//"+javaShortPath;
        String domainPath = domainPage.replace(".","//");
        return path+"//"+domainPath;
    }

    public String getServiceRealPath(){
        String path = PathConfig.getProjectPath()+"//"+javaShortPath;
        String servicePath = "";
        if(servicePage!=null) {
             servicePath = servicePage.replace(".", "//");
        }else{
            servicePath = parentPacke.replace(".","//")+"//service";
        }
        return path+"//"+servicePath;
    }

    public String getDaoRealPath(){
        String path = PathConfig.getProjectPath()+"//"+javaShortPath;
        String daoPath = "";
        if(daoPage!=null) {
             daoPath = daoPage.replace(".", "//");
        }else{
            daoPath = parentPacke.replace(".","//")+"//dao";
        }
        return path+"//"+daoPath;
    }

    public String getControllerRealPath(){
        String path = PathConfig.getProjectPath()+"//"+javaShortPath;
        String controllerPath = "";
        if(controllerPage!=null) {
             controllerPath = controllerPage.replace(".", "//");
        }else{
            controllerPath = parentPacke.replace(".","//")+"//web";
        }
        return path+"//"+controllerPath;
    }
}

import java.io.*;

public abstract class PathConfig {

    //获取当前项目路径 如G:\spring-boot-first\spring-boot-first
    public static String getProjectPath(){
       String path = System.getProperty("user.dir");
       return path.replace("\\","//");
    }

   //换行
   public static String newLine(){
        return System.getProperty("line.separator");
   }

   public static void copyToFile(File file, String content){
       BufferedWriter bw = null;
       try {
           bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
           bw.write(content);
           bw.flush();
       }catch (Exception e){
           throw new RuntimeException(e);
       }finally {
           if(bw!=null){
               try {
                   bw.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
   }
}


import java.io.File;

public class FacedeBuilder {
    private ControllerBuilder controllerBuilder;
    private ServiceBuilder serviceBuilder ;
    private DaoBuilder daoBudiler;

    private CoreConfig coreConfig;

    public FacedeBuilder(CoreConfig config){
        this.coreConfig = config;
        controllerBuilder = new ControllerBuilder(config);
        serviceBuilder = new ServiceBuilder(config);
        daoBudiler = new DaoBuilder(config);
    }

    private void loadClassName(){
       String path = coreConfig.getDomainRealPath();
        File filePath = new File(path);
        System.out.println(filePath);
        if(!filePath.exists())
            throw new RuntimeException("文件路径不存在请检测是否配置正确");
       File[] files = filePath.listFiles();
       if(files!=null){
           for(File file:files){
               if(file.isDirectory())
                   continue;
               String fileName = file.getName();
               if(fileName.endsWith(".java")){
                   String data = fileName.replace(".java","");
                   coreConfig.addClassName(data);
               }
           }
       }
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>加载类名完成>>>>>>>>>>>>>>>>>>>>>>>>>");
    }

    private void check(){
        if (coreConfig.getCorePage()==null){
            throw new RuntimeException("请配置核心包地方");
        }
        if(coreConfig.getParentPacke()==null&&coreConfig.getServicePage()==null&&coreConfig.getDaoPage()==null&&coreConfig.getControllerPage()==null)
            throw new RuntimeException("请配置生成dao,service,controller的包名");
        if(coreConfig.getJavaShortPath()==null){
            throw new RuntimeException("请配置java的短路径");
        }
        if(coreConfig.getDomainPage()==null){
            throw new RuntimeException("请配置java对象存放的包");
        }
        if(coreConfig.getDaoPage()==null){
            String daoPage = coreConfig.getParentPacke()+".dao";
            coreConfig.setDaoPage(daoPage);
        }
        if(coreConfig.getServicePage()==null){
            String servicePage = coreConfig.getParentPacke()+".service";
            coreConfig.setServicePage(servicePage);
        }
        if(coreConfig.getControllerPage()==null){
            String webPage = coreConfig.getParentPacke()+".web";
            coreConfig.setControllerPage(webPage);
        }
    }


    public void create(){
        check();
        loadClassName();
        if(coreConfig.isOpenDao()){
            daoBudiler.create();
        }
        if(coreConfig.isOpenService()){
            serviceBuilder.create();
        }
        if(coreConfig.isOpenController()){
            controllerBuilder.create();
        }
    }
}

================使用===================

import com.example.demo.init.CoreConfig;
import com.example.demo.init.FacedeBuilder;
import com.github.pagehelper.PageHelper;

public class TestMain {
    public static void main(String[] args) {
        CoreConfig coreConfig = new CoreConfig();
        //指定java相对项目下那个地方。我的是idea它的路径是这样
        coreConfig.setJavaShortPath("src//main//java");
        //制定实体类包路径
        coreConfig.setDomainPage("com.example.demo.domain");
        //是否生成controller层默认生成service,dao
        coreConfig.setOpenController(true);
//        coreConfig.setDaoPage("com.example.demo.test.dao");
//        coreConfig.setControllerPage("com.example.demo.test.web");
        //如果你的service,dao,controller的父包相同只需指定父包
        coreConfig.setParentPacke("com.example.demo.test");
        //制定baseDao那些类放的包路径
        coreConfig.setCorePage("com.example.demo.core");
        FacedeBuilder faceBuidler = new FacedeBuilder(coreConfig);
        faceBuidler.create();
    }
}


结果如下面表示成功了

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>加载类名完成>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>生成 ClassRoomEntityDaoImpl 完成
>>>>>>>>>>>>>>>>>>>>>>生成 PersonEntityDaoImpl 完成
>>>>>>>>>>>>>>>>>>>>>>生成 StudentEntityDaoImpl 完成
>>>>>>>>>>>>>>>>>>>>>>生成 StudentTeacherEntityDaoImpl 完成
>>>>>>>>>>>>>>>>>>>>>>生成 TeacherEntityDaoImpl 完成
>>>>>>>>>>>>>>>>>>>>>>生成 TestEntityDaoImpl 完成
>>>>>>>>>>>>>>>>>>>>>>生成 UserEntityDaoImpl 完成
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>dao层代码生成完成>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>生成 ClassRoomEntityServiceImpl 完成
>>>>>>>>>>>>>>>>>>>>>>生成 PersonEntityServiceImpl 完成
>>>>>>>>>>>>>>>>>>>>>>生成 StudentEntityServiceImpl 完成
>>>>>>>>>>>>>>>>>>>>>>生成 StudentTeacherEntityServiceImpl 完成
>>>>>>>>>>>>>>>>>>>>>>生成 TeacherEntityServiceImpl 完成
>>>>>>>>>>>>>>>>>>>>>>生成 TestEntityServiceImpl 完成
>>>>>>>>>>>>>>>>>>>>>>生成 UserEntityServiceImpl 完成
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>service层代码生成完成>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>生成 ClassRoomEntityController 完成
>>>>>>>>>>>>>>>>>>>>>>生成 PersonEntityController 完成
>>>>>>>>>>>>>>>>>>>>>>生成 StudentEntityController 完成
>>>>>>>>>>>>>>>>>>>>>>生成 StudentTeacherEntityController 完成
>>>>>>>>>>>>>>>>>>>>>>生成 TeacherEntityController 完成
>>>>>>>>>>>>>>>>>>>>>>生成 TestEntityController 完成
>>>>>>>>>>>>>>>>>>>>>>生成 UserEntityController 完成
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>web层代码生成完成>>>>>>>>>>>>>>>>>>>

注意上面的类放入到一个包下,这个架构前提是你的项目使用是jpa。祝你好运


好像每个Dao上面的方法都要加上@Transactional不然会出现数据库连接已经用完了,可能是代码service层没有添加Transactional注解

你可能感兴趣的:(制作小框架,spring高级应用)