1.在resources先新建mybatis-generator.xml资源文件
2.数据库数据的生成,我使用的word的可视化数据生成yml文件简单、方便,你可以去我的百度提取
链接:https://pan.baidu.com/s/1iNaEubwrQk9UvUO2aD3UOw
提取码:LONG
--- 你可以 ( 数据表_tool生成用.xlsm ) 这个文档就是数据库数据表的新建,非常方便观看和使用,然后用 ( genfile.xlsm) 生成 ( fieldDef.yml ) ,可以将yml放在resources的资源文件夹
3.将fieldDef.yml的文件生成数据库的数据表,先install在html调用生成接口all
@RestController
@RequestMapping(value = "gen")
public class GenToolsController {
@Autowired
DomainGenerator domainGenerator;
@Autowired
RepoGenerator repoGeregenerator;
@Autowired
CtrlGenerator ctrlGenerator;
@GetMapping("/all")
public String all() throws Exception {
domainGenerator.execute();
repoGeregenerator.execute();
ctrlGenerator.execute();
return "OK";
}
@GetMapping("/domain")
public String domain() throws Exception {
domainGenerator.execute();
return "OK";
}
@GetMapping("/repo")
public String repo() throws Exception {
repoGeregenerator.execute();
return "OK";
}
@GetMapping("/ctrl")
public String ctrl() throws Exception {
ctrlGenerator.execute();
return "OK";
}
}
调用all接口就可以在数据库生成数据表
同时还有几个
@Component
public class CtrlGenerator {
private GenProperties genProperties;
@Autowired
public CtrlGenerator(GenProperties genProperties) {
this.genProperties = genProperties;
}
public void execute() throws Exception {
String projectDir = this.getClass().getResource("/").getPath().replace("target/classes/", "");
File distDir = new File(projectDir, "src/main/java/com/test/demoApp/gen/controller");
System.out.println(distDir);
System.out.println("开始生成");
String[] types = {"Long", "String"};
List typeList = Arrays.asList(types);
genProperties.getControllers().forEach(item -> {
try {
String domainName = item.getDomain();
GenProperties.DomainConf domainConf = genProperties.findDomian(domainName);
String repoName = item.getRepository();
String ctrlName = item.getName();
String tagsName = item.getTags();
List fileLineList = new ArrayList<>();
fileLineList.add("package com.test.demoApp.gen.controller;");
fileLineList.add("");
fileLineList.add("import com.querydsl.core.types.dsl.BooleanExpression;");
fileLineList.add("import com.querydsl.jpa.impl.JPAQueryFactory;");
fileLineList.add("import com.test.demoApp.fixed.common.*;");
fileLineList.add("import com.test.demoApp.gen.domain.*;");
fileLineList.add("import com.test.demoApp.gen.repository.*;");
fileLineList.add("import io.swagger.annotations.Api;");
fileLineList.add("import io.swagger.annotations.ApiOperation;");
fileLineList.add("import io.swagger.annotations.ApiParam;");
fileLineList.add("import org.apache.commons.lang.StringUtils;");
fileLineList.add("import org.springframework.beans.factory.annotation.Autowired;");
fileLineList.add("import org.springframework.http.HttpStatus;");
fileLineList.add("import org.springframework.transaction.annotation.Transactional;");
fileLineList.add("import org.springframework.web.bind.annotation.*;");
fileLineList.add("import java.sql.Timestamp;");
fileLineList.add("import java.math.BigDecimal;");
fileLineList.add("import java.util.*;");
fileLineList.add("");
fileLineList.add("@Api(value = \""+WordUtils.uncapitalize(domainName)+"\", tags = \"" +tagsName+ "\")");
fileLineList.add("@RestController");
fileLineList.add("@RequestMapping(value = \"/gen/"+ WordUtils.uncapitalize(domainName)+"\")");
fileLineList.add("@SuppressWarnings(\"unchecked\")");
fileLineList.add("public class "+ctrlName+" {");
fileLineList.add("");
fileLineList.add(" @Autowired");
fileLineList.add(" "+repoName+" "+WordUtils.uncapitalize(repoName)+";");
fileLineList.add("");
fileLineList.add(" @Autowired");
fileLineList.add(" JPAQueryFactory queryFactory;");
fileLineList.add("");
// 单条数据检索方法生成
fileLineList.add(" @ApiOperation(value = \"查询单条\",");
fileLineList.add(" notes = \"通过id检索\")");
fileLineList.add(" @GetMapping(value = \"/queryOne\")");
fileLineList.add(" @ResponseStatus(code = HttpStatus.OK)");
fileLineList.add(" public ApiResult<"+domainName+"> query(");
fileLineList.add(" @RequestParam(required = false) Long id) {");
fileLineList.add(" "+domainName+" data = " + WordUtils.uncapitalize(repoName) + ".getOne(id);;");
fileLineList.add(" return ApiResultBuilder.create().code(ApiResultCode.Success.code()).msg(ApiResultCode.Success.msg())");
fileLineList.add(" .data(data).build();");
fileLineList.add(" }");
fileLineList.add("");
// 分页检索方法生成
fileLineList.add(" @ApiOperation(value = \"查询\",");
fileLineList.add(" notes = \"支持分页查询,默认返回10条记录\")");
fileLineList.add(" @GetMapping(value = \"/query\")");
fileLineList.add(" @ResponseStatus(code = HttpStatus.OK)");
fileLineList.add(" public ApiResult> query(");
fileLineList.add(" @RequestParam(required = false) Long id,");
List domainFields = domainConf.getFields();
domainFields.forEach(fieldDef ->{
String[] fieldInfo = StringUtils.splitPreserveAllTokens(fieldDef, "|");
String comment = fieldInfo[0];
String fieldName = fieldInfo[1];
String fieldType = fieldInfo[2];
String relation = fieldInfo[3];
String mainTableFlag = fieldInfo[4];
if (StringUtils.isEmpty(relation)) {
fileLineList.add(" @RequestParam(required = false) @ApiParam(value = \""+comment+"\") "+fieldType+" "+fieldName+",");
}
});
fileLineList.add(" @RequestParam(required = false) @ApiParam(value = \"页码\") Long page,");
fileLineList.add(" @RequestParam(required = false) @ApiParam(value = \"限制条数\") Long limit) {");
fileLineList.add("");
fileLineList.add(" // 关联表");
fileLineList.add(" Q"+domainName+" q"+domainName+" = Q"+domainName+"."+WordUtils.uncapitalize(domainName)+";");
fileLineList.add("");
fileLineList.add(" // 检索条件构造");
fileLineList.add(" BooleanExpression whereExp = q"+domainName+".id.eq(q"+domainName+".id);");
fileLineList.add(" if (id != null) {");
fileLineList.add(" whereExp = whereExp.and(q"+domainName+".id.eq(id));");
fileLineList.add(" }");
domainFields.forEach(fieldDef ->{
String[] fieldInfo = StringUtils.splitPreserveAllTokens(fieldDef, "|");
String comment = fieldInfo[0];
String fieldName = fieldInfo[1];
String fieldType = fieldInfo[2];
String relation = fieldInfo[3];
String mainTableFlag = fieldInfo[4];
if (StringUtils.isEmpty(relation)) {
if ("Long".equals(fieldType)
|| "Timestamp".equals(fieldType)
|| "BigDecimal".equals(fieldType)
|| "Integer".equals(fieldType)
|| "Double".equals(fieldType)
|| "Float".equals(fieldType)
|| "Short".equals(fieldType)
|| "Byte".equals(fieldType)) {
fileLineList.add(" if ("+fieldName+" != null) {");
fileLineList.add(" whereExp = whereExp.and(q"+domainName+"."+fieldName+".eq("+fieldName+"));");
fileLineList.add(" }");
} else if ("String".equals(fieldType)) {
fileLineList.add(" if (StringUtils.isNotEmpty("+fieldName+")) {");
fileLineList.add(" whereExp = whereExp.and(q"+domainName+"."+fieldName+".eq("+fieldName+"));");
fileLineList.add(" }");
}
}
});
fileLineList.add("");
fileLineList.add(" // 件数取得");
fileLineList.add(" Long count = queryFactory.selectFrom(q"+domainName+").where(whereExp).fetchCount();");
fileLineList.add(" if (count == 0) {");
fileLineList.add(" return ApiResultBuilder.create().code(ApiResultCode.Fail.code()).msg(\"没有检索到任何数据\").build();");
fileLineList.add(" }");
fileLineList.add("");
fileLineList.add(" // 分页控制信息构造");
fileLineList.add(" ApiPagination pagination = new ApiPagination(page, limit, count);");
fileLineList.add("");
fileLineList.add(" // 数据检索");
fileLineList.add(" List<"+domainName+"> data = queryFactory");
fileLineList.add(" .selectFrom(q"+domainName+")");
fileLineList.add(" .where(whereExp)");
fileLineList.add(" .offset(pagination.getOffset())");
fileLineList.add(" .limit(pagination.getLimit())");
fileLineList.add(" .fetch();");
fileLineList.add("");
fileLineList.add(" // 分页数据返回");
fileLineList.add(" return ApiResultBuilder.create().code(0).msg(\"成功返回\").data(data).pagination(pagination).build();");
fileLineList.add(" }");
fileLineList.add("");
// 插入/更新方法生成
fileLineList.add(" @ApiOperation(value = \"保存\")");
fileLineList.add(" @PostMapping(value = \"/save\")");
fileLineList.add(" @ResponseStatus(code = HttpStatus.OK)");
fileLineList.add(" @Transactional");
fileLineList.add(" public ApiResult<"+domainName+"> save(@RequestBody ApiParams<"+domainName+"> params) {");
fileLineList.add(" "+domainName+" target = null;");
//fileLineList.add(" Q"+domainName+" q"+domainName+" = Q"+domainName+"."+WordUtils.uncapitalize(domainName)+";");
fileLineList.add("");
fileLineList.add(" // 新建");
fileLineList.add(" if (params.getData().getId() == null) {");
fileLineList.add(" target = params.getData();");
fileLineList.add(" target.setCreatedTime(new Timestamp(System.currentTimeMillis()));");
fileLineList.add(" target.setLastUpdateTime(new Timestamp(System.currentTimeMillis()));");
fileLineList.add(" // 更新");
fileLineList.add(" } else {");
fileLineList.add(" target = "+WordUtils.uncapitalize(repoName)+".getOne(params.getData().getId());");
fileLineList.add(" if (params.getData().getVersion() != target.getVersion()) {");
fileLineList.add(" return ApiResultBuilder.create().code(ApiResultCode.DataIllegality.code())");
fileLineList.add(" .msg(ApiResultCode.DataIllegality.msg()).build();");
fileLineList.add(" }");
domainFields.forEach(fieldDef ->{
String[] fieldInfo = StringUtils.splitPreserveAllTokens(fieldDef, "|");
String comment = fieldInfo[0];
String fieldName = fieldInfo[1];
String fieldType = fieldInfo[2];
String relation = fieldInfo[3];
String mainTableFlag = fieldInfo[4];
if ("Long".equals(fieldType)
|| "Timestamp".equals(fieldType)
|| "BigDecimal".equals(fieldType)
|| "Integer".equals(fieldType)
|| "Double".equals(fieldType)
|| "Float".equals(fieldType)
|| "Short".equals(fieldType)
|| "Byte".equals(fieldType)) {
fileLineList.add(" if (params.getData().get"+WordUtils.capitalize(fieldName)+"() != null) {");
fileLineList.add(" target.set"+WordUtils.capitalize(fieldName)+"(params.getData().get"+WordUtils.capitalize(fieldName)+"());");
fileLineList.add(" }");
} else if ("String".equals(fieldType)) {
fileLineList.add(" if (StringUtils.isNotEmpty(params.getData().get"+WordUtils.capitalize(fieldName)+"())) {");
fileLineList.add(" target.set"+WordUtils.capitalize(fieldName)+"(params.getData().get"+WordUtils.capitalize(fieldName)+"());");
fileLineList.add(" }");
}
});
fileLineList.add(" target.setLastUpdateTime(new Timestamp(System.currentTimeMillis()));");
fileLineList.add(" }");
fileLineList.add(" target = "+WordUtils.uncapitalize(repoName)+".save(target);");
fileLineList.add(" return ApiResultBuilder.create().code(ApiResultCode.Success.code()).msg(ApiResultCode.Success.msg())");
fileLineList.add(" .data(target).build();");
fileLineList.add(" }");
fileLineList.add("");
// 删除方法
fileLineList.add(" @ApiOperation(value = \"物理删除\")");
fileLineList.add(" @PostMapping(value = \"/delete\")");
fileLineList.add(" @ResponseStatus(code = HttpStatus.OK)");
fileLineList.add(" @Transactional");
fileLineList.add(" public ApiResult delete(@RequestBody ApiParams> deleteParams) {");
fileLineList.add("");
fileLineList.add(" if (deleteParams.getData() == null) {");
fileLineList.add(" return ApiResultBuilder.create()");
fileLineList.add(" .code(ApiResultCode.DataIllegality.code())");
fileLineList.add(" .msg(ApiResultCode.DataIllegality.msg()).build();");
fileLineList.add(" }");
fileLineList.add("");
fileLineList.add(" for (String id : deleteParams.getData()) {");
fileLineList.add(" "+WordUtils.uncapitalize(repoName)+".deleteById(Long.parseLong(id));");
fileLineList.add(" }");
fileLineList.add(" return ApiResultBuilder.create().code(ApiResultCode.Success.code()).msg(\"删除成功\").build();");
fileLineList.add(" }");
fileLineList.add("");
fileLineList.add("}");
fileLineList.add("");
File distFile = new File(distDir, ctrlName + ".java");
if (distFile.exists()) {
distFile.delete();
}
RandomAccessFile aFile = new RandomAccessFile(distFile, "rw");
FileChannel fileChannel = aFile.getChannel();
byte[] bytes = StringUtils.join(fileLineList, '\n').getBytes("UTF-8");
ByteBuffer buf= ByteBuffer.allocate(bytes.length);
buf.clear();
buf.put(bytes);
buf.flip();
while (buf.hasRemaining()) {
fileChannel.write(buf);
}
fileChannel.close();
System.out.println("----> " + ctrlName + " 完成");
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
@Component
public class DomainGenerator {
private GenProperties genProperties;
@Autowired
public DomainGenerator(GenProperties genProperties) {
this.genProperties = genProperties;
}
public void execute() throws Exception {
String projectDir = this.getClass().getResource("/").getPath().replace("target/classes/", "");
File distDir = new File(projectDir, "src/main/java/com/test/demoApp/gen/domain");
System.out.println(distDir);
genProperties.getDomains().forEach(item -> {
try{
List fileLineList = new ArrayList<>();
String domainClassName = item.getName();
fileLineList.add("package com.test.demoApp.gen.domain;");
fileLineList.add("import com.test.demoApp.fixed.domain.*;");
fileLineList.add("import com.fasterxml.jackson.annotation.JsonIgnore;");
fileLineList.add("import com.fasterxml.jackson.annotation.JsonIgnoreProperties;");
fileLineList.add("import org.hibernate.annotations.DynamicInsert;");
fileLineList.add("import org.hibernate.annotations.DynamicUpdate;");
fileLineList.add("");
fileLineList.add("import javax.persistence.*;");
fileLineList.add("import java.io.Serializable;");
fileLineList.add("import java.util.*;");
fileLineList.add("import java.sql.Timestamp;");
fileLineList.add("import java.math.BigDecimal;");
fileLineList.add("");
fileLineList.add("@Entity");
fileLineList.add("@DynamicUpdate(true)");
fileLineList.add("@DynamicInsert(true)");
fileLineList.add("@JsonIgnoreProperties(value = {\"handler\",\"hibernateLazyInitializer\",\"fieldHandler\"})");
fileLineList.add("@Table(name = \"BIZ_" + domainClassName.toUpperCase() + "\")");
fileLineList.add("public class " + domainClassName + " extends BaseEntity implements Serializable {");
fileLineList.add(" private static final long serialVersionUID = 1L;");
fileLineList.add("");
List domainFields = item.getFields();
domainFields.forEach(fieldDef ->{
String[] fieldInfo = StringUtils.splitPreserveAllTokens(fieldDef, "|");
String comment = fieldInfo[0];
String fieldName = fieldInfo[1];
String fieldType = fieldInfo[2];
String relation = fieldInfo[3];
String mainTableFlag = fieldInfo[4];
fileLineList.add(" /** " + comment + " */");
if ("ManyToOne".equals(relation)) {
fileLineList.add(" @JsonIgnore");
fileLineList.add(" @ManyToOne");
fileLineList.add(" @JoinColumn(name = \""+fieldName+"_id\")");
fileLineList.add(" private " + fieldType + " " + fieldName + ";");
} else if ("OneToMany".equals(relation)) {
fileLineList.add(" @OneToMany(mappedBy = \"parent"+ domainClassName +"\", cascade = CascadeType.ALL, orphanRemoval = true)");
if (StringUtils.contains(fieldType, "Set")) {
fileLineList.add(" private " + fieldType + " " + fieldName + " = new TreeSet<>();");
} else {
fileLineList.add(" private " + fieldType + " " + fieldName + " = new ArrayList<>();");
}
} else if("ManyToMany".equals(relation)) {
if ("main".equals(mainTableFlag)) {
String mainTableName = domainClassName;
String slaveTableName = fieldName.replace("List", "");
fileLineList.add(" @ManyToMany(fetch = FetchType.EAGER)");
fileLineList.add(" @JoinTable(");
fileLineList.add(" name=\"" + mainTableName + "_" + slaveTableName + "\",");
fileLineList.add(" joinColumns=@JoinColumn(name=\"" + mainTableName + "_ID" + "\", referencedColumnName=\"ID\"),");
fileLineList.add(" inverseJoinColumns=@JoinColumn(name=\"" + slaveTableName + "_ID" + "\", referencedColumnName=\"ID\"))");
if (StringUtils.contains(fieldType, "Set")) {
fileLineList.add(" private " + fieldType + " " + fieldName + " = new TreeSet<>();");
} else {
fileLineList.add(" private " + fieldType + " " + fieldName + " = new ArrayList<>();");
}
} else {
fileLineList.add(" @JsonIgnore");
fileLineList.add(" @ManyToMany(mappedBy=\"" + WordUtils.uncapitalize(domainClassName) + "List" + "\", fetch = FetchType.LAZY)");
if (StringUtils.contains(fieldType, "Set")) {
fileLineList.add(" private " + fieldType + " " + fieldName + " = new TreeSet<>();");
} else {
fileLineList.add(" private " + fieldType + " " + fieldName + " = new ArrayList<>();");
}
}
} else if ("OneToOne".equals(relation)) {
if ("main".equals(mainTableFlag)) {
fileLineList.add(" @OneToOne(mappedBy = \""+WordUtils.uncapitalize(domainClassName)+"\", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)");
fileLineList.add(" private " + fieldType + " " + fieldName + ";");
} else {
fileLineList.add(" @JsonIgnore");
fileLineList.add(" @OneToOne(fetch = FetchType.LAZY)");
fileLineList.add(" @JoinColumn(name = \""+fieldName+"_id\")");
fileLineList.add(" private " + fieldType + " " + fieldName + ";");
}
} else {
fileLineList.add(" private " + fieldType + " " + fieldName + ";");
}
});
domainFields.forEach(fieldDef ->{
String[] fieldInfo = StringUtils.splitPreserveAllTokens(fieldDef, "|");
String comment = fieldInfo[0];
String fieldName = fieldInfo[1];
String fieldType = fieldInfo[2];
String relation = fieldInfo[3];
// GET方法
fileLineList.add(" /**");
fileLineList.add(" * 获取 " + comment);
fileLineList.add(" *");
fileLineList.add(" * @return "+fieldName+" "+comment);
fileLineList.add(" */");
fileLineList.add(" public "+fieldType+" get"+StringUtils.capitalize(fieldName)+"() {");
fileLineList.add(" return this."+fieldName+";");
fileLineList.add(" }");
fileLineList.add("");
// SET方法
fileLineList.add(" /**");
fileLineList.add(" * 设置 " + comment);
fileLineList.add(" *");
fileLineList.add(" * @param "+fieldName+" "+comment);
fileLineList.add(" */");
fileLineList.add(" public void set"+StringUtils.capitalize(fieldName)+"("+fieldType+" "+fieldName+") {");
fileLineList.add(" this."+fieldName+" = "+fieldName+";");
fileLineList.add(" }");
fileLineList.add("");
});
fileLineList.add("}");
File distFile = new File(distDir, domainClassName + ".java");
if (distFile.exists()) {
distFile.delete();
}
RandomAccessFile aFile = new RandomAccessFile(distFile, "rw");
FileChannel fileChannel = aFile.getChannel();
byte[] bytes = StringUtils.join(fileLineList, '\n').getBytes("UTF-8");
ByteBuffer buf= ByteBuffer.allocate(bytes.length);
buf.clear();
buf.put(bytes);
buf.flip();
while (buf.hasRemaining()) {
fileChannel.write(buf);
}
fileChannel.close();
System.out.println("----> " + domainClassName + " 完成");
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
@Component
@ConfigurationProperties(prefix = "gen")
public class GenProperties {
private List domains;
private List repositorys;
private List controllers;
public GenProperties.DomainConf findDomian(String domainName) {
for (DomainConf domainConf : domains) {
if (domainConf.getName().equals(domainName)) {
return domainConf;
}
}
return null;
}
public List getDomains() {
return domains;
}
public void setDomains(List domains) {
this.domains = domains;
}
public List getRepositorys() {
return repositorys;
}
public void setRepositorys(List repositorys) {
this.repositorys = repositorys;
}
public List getControllers() {
return controllers;
}
public void setControllers(List controllers) {
this.controllers = controllers;
}
public static class DomainConf {
private String name;
private List fields;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List getFields() {
return fields;
}
public void setFields(List fields) {
this.fields = fields;
}
}
public static class RepoConf {
private String name;
private String domain;
private String pkType;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getPkType() {
return pkType;
}
public void setPkType(String pkType) {
this.pkType = pkType;
}
}
public static class CtrlConf {
private String name;
private String domain;
private String repository;
private String tags;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getRepository() {
return repository;
}
public void setRepository(String repository) {
this.repository = repository;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
}
}
@Component
public class RepoGenerator {
private GenProperties genProperties;
@Autowired
public RepoGenerator(GenProperties genProperties) {
this.genProperties = genProperties;
}
public void execute() throws Exception {
String projectDir = this.getClass().getResource("/").getPath().replace("target/classes/", "");
File distDir = new File(projectDir, "src/main/java/com/test/demoApp/gen/repository");
System.out.println(distDir);
System.out.println("开始生成");
genProperties.getRepositorys().forEach(item -> {
try {
String domianClassName = item.getDomain();
String pkType = item.getPkType();
String repoClassName = domianClassName + "RepositoryDsl";
if (StringUtils.isNotEmpty(item.getName())) {
repoClassName = item.getName();
}
String[] strings = {
"package com.test.demoApp.gen.repository;",
"",
"import com.test.demoApp.gen.domain."+ domianClassName + ";",
"import org.springframework.data.jpa.repository.JpaRepository;",
"import org.springframework.data.querydsl.QuerydslPredicateExecutor;",
"",
"public interface "+ repoClassName +" extends JpaRepository<" + domianClassName + ", " + pkType + ">,QuerydslPredicateExecutor<" + domianClassName + "> {",
"}"
};
File distFile = new File(distDir, repoClassName + ".java");
if (distFile.exists()) {
distFile.delete();
}
RandomAccessFile aFile = new RandomAccessFile(distFile, "rw");
FileChannel fileChannel = aFile.getChannel();
byte[] bytes = StringUtils.join(strings, '\n').getBytes("UTF-8");
ByteBuffer buf= ByteBuffer.allocate(bytes.length);
buf.clear();
buf.put(bytes);
buf.flip();
while (buf.hasRemaining()) {
fileChannel.write(buf);
}
fileChannel.close();
System.out.println("----> " + repoClassName + " 完成");
} catch (Exception e) {
e.printStackTrace();
}
});
System.out.println("生成结束");
}
}
有这几个就可以用了注意一下路劲的配置就行了