前言:
jpa的使用可以采用jpa接口规范或采用entityManger但用起来感觉不是很爽,以前用过mybatisplugin感觉很好用
现在就按照他的思想做了个
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 extends Serializable> 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
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 extends Serializable> 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
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 extends Serializable> 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 extends Serializable> 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注解