– 利用idea工具快速生成Springboot+JPA的项目基础架构
在idea中连接DB之后,根据图中指示
根据图中步骤:
找到对应Generate POJOs.groovy 文件。
–将下面的代码替换到Generate POJOs.groovy 文件中
–脚本生成 对应的【Entity,Repository,Service,ServiceImpl ,Resp,Rep,Controller】
–生成RESTful的URL
import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import java.text.SimpleDateFormat
config = [
impSerializable : true,
extendBaseEntity : false,
extendBaseService: false,
useLombok : false, // 会生成get、set方法
// 不生成哪个就注释哪个
generateItem : [
"Entity",
"Service",
"Controller",//第一步
"Repository",
"Resp",
"Req",
// "RepositoryCustom",
// "RepositoryImpl",
"ServiceImpl",
]
]
baseEntityPackage = "com.dz.demo.framework.base.BaseEntity"
baseServicePackage = "com.dz.demo.framework.base.BaseService"
baseEntityProperties = ["id", "createDate", "lastModifiedDate", "version"]
typeMapping = [
(~/(?i)bool|boolean|tinyint/) : "Boolean",
(~/(?i)bigint/) : "Long",
(~/int/) : "Integer",
(~/(?i)float|double|decimal|real/): "Double",
(~/(?i)datetime|timestamp/) : "java.util.Date",
(~/(?i)date/) : "java.sql.Date",
(~/(?i)time/) : "java.sql.Time",
(~/(?i)/) : "String"
]
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
SELECTION.filter {
it instanceof DasTable && it.getKind() == ObjectKind.TABLE
}.each {
generate(it, dir)
}
}
// 生成对应的文件
def generate(table, dir) {
def entityPath = "${dir.toString()}\\domain\\entity",
servicePath = "${dir.toString()}\\service",
respPath = "${dir.toString()}\\domain\\res",
reqPath = "${dir.toString()}\\domain\\req",
repPath = "${dir.toString()}\\repository",
// repImpPath = "${dir.toString()}\\repository\\impl",
serviceImplPath = "${dir.toString()}\\service\\impl",
controllerPath = "${dir.toString()}\\controller"
mkdirs([entityPath, servicePath, repPath, serviceImplPath, controllerPath, respPath, reqPath])
System.out.println(table.getName())
def entityName = javaName(table.getName(), true)
def fields = calcFields(table)
def basePackage = clacBasePackage(dir)
if (isGenerate("Resp")) {
genUTF8File(respPath, "${entityName}Resp.java").withPrintWriter { out -> genResp(out, table, entityName, fields, basePackage) }
}
if (isGenerate("Req")) {
genUTF8File(reqPath, "${entityName}Req.java").withPrintWriter { out -> genReq(out, table, entityName, fields, basePackage) }
}
if (isGenerate("Entity")) {
genUTF8File(entityPath, "${entityName}.java").withPrintWriter { out -> genEntity(out, table, entityName, fields, basePackage) }
}
if (isGenerate("Service")) {
genUTF8File(servicePath, "${entityName}Service.java").withPrintWriter { out -> genService(out, table, entityName, fields, basePackage) }
}
//第二步 记得改后面的方法
if (isGenerate("Controller")) {
genUTF8File(controllerPath, "${entityName}Controller.java").withPrintWriter { out -> genController(out, table, entityName, fields, basePackage) }
}
if (isGenerate("Repository")) {
genUTF8File(repPath, "${entityName}Repository.java").withPrintWriter { out -> genRepository(out, table, entityName, fields, basePackage) }
}
if (isGenerate("RepositoryCustom")) {
genUTF8File(repPath, "${entityName}RepositoryCustom.java").withPrintWriter { out -> genRepositoryCustom(out, entityName, basePackage) }
}
if (isGenerate("RepositoryImpl")) {
genUTF8File(repImpPath, "${entityName}RepositoryImpl.java").withPrintWriter { out -> genRepositoryImpl(out, table, entityName, fields, basePackage) }
}
if (isGenerate("ServiceImpl")) {
genUTF8File(serviceImplPath, "${entityName}ServiceImpl.java").withPrintWriter { out -> genServiceImpl(out, table, entityName, fields, basePackage) }
}
}
// 判断是否需要被生成
def isGenerate(itemName) {
config.generateItem.contains(itemName)
}
// 首字母小写转换
def theFirstToLowerCase(str) {
StringBuilder sb = new StringBuilder();
sb.append(str.substring(0, 1).toLowerCase())
sb.append(str.substring(1))
return sb.toString();
}
// 指定文件编码方式,防止中文注释乱码
def genUTF8File(dir, fileName) {
new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, fileName)), "utf-8"))
}
// 生成每个字段
def genProperty(out, field) {
out.println ""
out.println "\t/**"
out.println "\t * ${field.comment.toString()}"
// out.println "\t * default value: ${field.default}"
out.println "\t */"
// 默认表的第一个字段为主键
if (field.position == 1) {
out.println "\t@Id"
//自增主键需要
out.println "\t@GeneratedValue(strategy = GenerationType.IDENTITY)"
}
// 枚举不需要长度
out.println "\t@Column(name = \"${field.colum}\", nullable = ${!field.isNotNull}${field.dataType == "enum" ? "" : ""})"
out.println "\tprivate ${field.type} ${field.name};"
}
// 接受体和返回体生成每个字段
def genResp(out, field) {
out.println ""
out.println "\t/**"
out.println "\t * ${field.comment.toString()}"
// out.println "\t * default value: ${field.default}"
out.println "\t */"
out.println "\t@JsonProperty( \"${field.colum}\")"
out.println "\tprivate ${field.type} ${field.name};"
}
// 生成get、get方法
def genGetSet(out, field, entityName) {
// get
out.println "\t"
out.println "\tpublic ${field.type} get${field.name.substring(0, 1).toUpperCase()}${field.name.substring(1)}() {"
out.println "\t\treturn this.${field.name};"
out.println "\t}"
// set
out.println "\t"
out.println "\tpublic void set${field.name.substring(0, 1).toUpperCase()}${field.name.substring(1)}(${field.type} ${field.name}) {"
out.println "\t\tthis.${field.name} = ${field.name};"
out.println "\t}"
//build
out.println "\t"
out.println "\tpublic ${entityName} ${field.name.substring(0, 1).toUpperCase()}${field.name.substring(1)}(${field.type} ${field.name}) {"
out.println "\t\tthis.${field.name} = ${field.name};"
out.println "\t\treturn this;"
out.println "\t}"
}
// 生成实体类
def genEntity(out, table, entityName, fields, basePackage) {
out.println "package ${basePackage}.domain.entity;"
out.println ""
if (config.extendBaseEntity) {
// out.println "import $baseEntityPackage;"
}
out.println "import javax.persistence.*;"
out.println "import java.io.Serializable;;"
out.println ""
out.println "/**\n" +
" * @Description \n" +
" * @Author Mu\n" + //
" * @Date " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \n" +
" */"
if (config.useLombok) {
out.println "@Data"
}
out.println "@Entity"
out.println "@Table(name = \"${table.getName()}\")"
out.println "public class $entityName${config.extendBaseEntity ? " extends BaseEntity" : ""}${config.impSerializable ? " implements Serializable" : ""} {"
if (config.extendBaseEntity) {
fields = fields.findAll { it ->
!baseEntityProperties.any { it1 -> it1 == it.name }
}
}
fields.each() {
genProperty(out, it)
}
if (!config.useLombok) {
fields.each() {
genGetSet(out, it, entityName)
}
}
out.println "}"
}
// 生成返回值
def genResp(out, table, entityName, fields, basePackage) {
out.println "package ${basePackage}.domain.res;"
out.println ""
if (config.extendBaseEntity) {
// out.println "import $baseEntityPackage;"
}
out.println "import javax.persistence.*;"
out.println "import com.fasterxml.jackson.annotation.JsonIgnoreProperties;"
out.println "import com.fasterxml.jackson.annotation.JsonProperty;"
out.println "import java.io.Serializable;"
out.println ""
out.println "/**\n" +
" * @Description \n" +
" * @Author Mu\n" + //
" * @Date " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \n" +
" */"
out.println "@JsonIgnoreProperties(ignoreUnknown = true) "
out.println "public class ${entityName}Resp${config.extendBaseService ? " extends BaseService<$entityName, ${fields[0].type}>" : ""}{"
fields.each() {
genResp(out, it)
}
if (!config.useLombok) {
fields.each() {
genGetSet(out, it, entityName + "Resp")
}
}
out.println "}"
}
// 生成接收值
def genReq(out, table, entityName, fields, basePackage) {
out.println "package ${basePackage}.domain.req;"
out.println ""
if (config.extendBaseEntity) {
// out.println "import $baseEntityPackage;"
}
out.println "import javax.persistence.*;"
out.println "import com.fasterxml.jackson.annotation.JsonIgnoreProperties;"
out.println "import com.fasterxml.jackson.annotation.JsonProperty;"
out.println "import java.io.Serializable;"
out.println ""
out.println "/**\n" +
" * @Description \n" +
" * @Author Mu\n" + //
" * @Date " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \n" +
" */"
out.println "@JsonIgnoreProperties(ignoreUnknown = true) "
out.println "public class ${entityName}Req${config.extendBaseService ? " extends BaseService<$entityName, ${fields[0].type}>" : ""}{"
fields.each() {
genResp(out, it)
}
if (!config.useLombok) {
fields.each() {
genGetSet(out, it, entityName + "Req")
}
}
out.println "}"
}
// 生成Service
def genService(out, table, entityName, fields, basePackage) {
out.println "package ${basePackage}.service;"
out.println ""
// out.println "import ${basePackage}.repository.${entityName}Repository;"
if (config.extendBaseService) {
// out.println "import $baseServicePackage;"
out.println "import ${basePackage}.domain.entity.$entityName;"
}
out.println "import ${basePackage}.domain.*;"
out.println "import org.springframework.stereotype.Service;"
out.println "import lombok.SneakyThrows;"
out.println "import ${basePackage}.domain.entity.*;"
out.println "import ${basePackage}.domain.res.*;"
out.println "import ${basePackage}.domain.req.*;"
out.println "import org.springframework.data.domain.Page;"
out.println "import java.util.List;"
out.println "import java.util.Optional;"
out.println ""
out.println "/**\n" +
" * @Description \n" +
" * @Author Mu\n" + //
" * @Date " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \n" +
" */"
out.println ""
out.println "public interface ${entityName}Service${config.extendBaseService ? " extends BaseService<$entityName, ${fields[0].type}>" : ""} {"
out.println ""
out.println "\t/**"
out.println "\t* queryAll"
out.println "\t* @return List<${entityName}Resp>"
out.println "\t*/"
out.println "\t@SneakyThrows"
out.println "\tList<${entityName}Resp> queryAll();"
out.println ""
out.println ""
out.println "\t/**"
out.println "\t* findById"
out.println "\t* @param id"
out.println "\t * @return ${entityName}"
out.println "\t*/"
out.println "\t@SneakyThrows"
out.println "\t ${entityName}Resp findById(long id);"
out.println ""
out.println "\t/**"
out.println "\t* create"
out.println "\t* @param resources"
out.println "\t* @return boolean"
out.println "\t*/"
out.println "\t@SneakyThrows"
out.println "\tvoid create(${entityName}Req resources);"
out.println ""
out.println "\t/**"
out.println "\t* update"
out.println "\t* @param resources"
out.println "\t* @return boolean"
out.println "\t*/"
out.println "\t@SneakyThrows"
out.println "\tvoid update(${entityName}Req resources);"
out.println ""
out.println "\t/**"
out.println "\t* deleteById"
out.println "\t* @param id"
out.println "\t* @return boolean"
out.println "\t*/"
out.println "\t@SneakyThrows"
out.println "\tvoid deleteById(long id);"
out.println ""
out.println "\t/**"
out.println "\t* listOfPage"
out.println "\t* @param pageSize ,pageNumber"
out.println "\t* @return Page<${entityName}>"
out.println "\t*/"
out.println "\t@SneakyThrows"
out.println "\tPage<${entityName}> listOfPage(int pageSize, int pageNumber);"
out.println "}"
}
// 生成Controller 第三步
def genController(out, table, entityName, fields, basePackage) {
out.println "package ${basePackage}.controller;"
out.println ""
// out.println "import ${basePackage}.repository.${entityName}Repository;"
if (config.extendBaseService) {
// out.println "import $baseServicePackage;"
out.println "import ${basePackage}.domain.entity.$entityName;"
}
out.println "import org.springframework.web.bind.annotation.RequestMapping;"
out.println "import org.springframework.web.bind.annotation.RestController;"
out.println "import ${basePackage}.service.${entityName}Service;"
out.println "import ${basePackage}.domain.res.*;"
out.println "import ${basePackage}.domain.req.*;"
out.println "import ${basePackage}.domain.entity.*;"
out.println "import lombok.SneakyThrows;"
out.println "import org.springframework.util.ObjectUtils;"
out.println "import org.springframework.beans.factory.annotation.Autowired;"
out.println "import org.springframework.web.bind.annotation.*;"
out.println "import org.springframework.validation.annotation.Validated;"
out.println ""
out.println "/**\n" +
" * @Description \n" +
" * @Author Mu\n" + //
" * @Date " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \n" +
" */"
out.println ""
out.println "@RestController"
out.println "@RequestMapping(\"/api/${entityName.substring(0, 1).toLowerCase()}${entityName.substring(1)}\")"//首字母小写
out.println "public class ${entityName}Controller${config.extendBaseService ? " extends BaseService<$entityName, ${fields[0].type}>" : ""} extends BaseController {"
out.println ""
out.println "\t@Autowired"
out.println "\tprivate ${entityName}Service " + theFirstToLowerCase("${entityName}") + "Service;"
out.println ""
out.println "\t@GetMapping()"
out.println "\t@SneakyThrows"
out.println "\tpublic Response query${entityName}("
out.println "\t @RequestParam(value = \"keyword\", required = false) String keyword,"
out.println "\t @RequestParam(value = \"page_number\", required = false) Integer pageNumber,"
out.println "\t @RequestParam(value = \"page_size\", required = false) Integer pageSize"
out.println "\t){"
out.println "\tif (ObjectUtils.isEmpty(pageNumber) || pageNumber < 1)"
out.println "\tpageNumber = 1;"
out.println "\tif (ObjectUtils.isEmpty(pageSize) || pageSize < 1)"
out.println "\tpageSize = 10;"
out.println " \t return Response.success(" + theFirstToLowerCase("${entityName}") + "Service.listOfPage(pageSize,pageNumber));"
out.println " \t //return Response.success(" + theFirstToLowerCase("${entityName}") + "Service.queryAll());"
out.println " \t}"
out.println ""
out.println "\t@PostMapping()"
out.println "\t@SneakyThrows"
out.println "\tpublic Response create${entityName}(@Validated @RequestBody ${entityName}Req resources){ "
out.println " \t" + theFirstToLowerCase("${entityName}") + "Service.create(resources);"
out.println " \treturn Response.success();"
out.println " \t}"
out.println ""
out.println "\t@DeleteMapping(\"/{id}\")"
out.println "\t@SneakyThrows"
out.println "\tpublic Response deleteById${entityName}(" +
" @PathVariable(value = \"id\") Long id){ "
out.println " \t" + theFirstToLowerCase("${entityName}") + "Service.deleteById(id);"
out.println " \treturn Response.success();"
out.println " \t}"
out.println ""
out.println "\t@PutMapping()"
out.println "\t@SneakyThrows"
out.println "\tpublic Response update${entityName}(@Validated @RequestBody ${entityName}Req resources){ "
out.println " \t" + theFirstToLowerCase("${entityName}") + "Service.update(resources);"
out.println " \treturn Response.success();"
out.println " \t}"
out.println ""
out.println "}"
}
// 生成Repository
def genRepository(out, table, entityName, fields, basePackage) {
out.println "package ${basePackage}.repository;"
out.println ""
out.println "import ${basePackage}.domain.entity.$entityName;"
out.println "import org.springframework.data.jpa.repository.JpaRepository;"
out.println "import org.springframework.data.jpa.repository.JpaSpecificationExecutor;"
out.println ""
out.println "/**\n" +
" * @Description \n" +
" * @Author Mu\n" + //
" * @Date " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \n" +
" */"
out.println ""
out.println "public interface ${entityName}Repository extends JpaRepository<$entityName, ${fields[0].type}>, JpaSpecificationExecutor<$entityName>{"
out.println ""
out.println "}"
}
// 生成RepositoryCustom
def genRepositoryCustom(out, entityName, basePackage) {
out.println "package ${basePackage}.repository;"
out.println ""
out.println "public interface ${entityName}RepositoryCustom {"
out.println ""
out.println "}"
}
// 生成RepositoryImpl
def genRepositoryImpl(out, table, entityName, fields, basePackage) {
out.println "package ${basePackage}.repository.impl;"
out.println ""
out.println "import ${basePackage}.repository.${entityName}RepositoryCustom;"
out.println "import org.springframework.stereotype.Repository;"
out.println ""
out.println "import javax.persistence.EntityManager;"
out.println "import javax.persistence.PersistenceContext;"
out.println ""
out.println "@Repository"
out.println "public class ${entityName}RepositoryImpl implements ${entityName}RepositoryCustom {"
out.println ""
out.println "\t@PersistenceContext"
out.println "\tprivate EntityManager em;"
out.println "}"
}
// 生成ServiceImpl
def genServiceImpl(out, table, entityName, fields, basePackage) {
out.println "package ${basePackage}.service.impl;"
out.println ""
out.println "import ${basePackage}.service.${entityName}Service;"
out.println "import ${basePackage}.repository.${entityName}Repository;"
out.println "import org.springframework.beans.factory.annotation.Autowired;"
out.println "import org.springframework.stereotype.Service;"
out.println "import ${basePackage}.domain.res.*;"
out.println "import lombok.SneakyThrows;"
out.println "import java.util.Optional;"
out.println "import ${basePackage}.domain.req.*;"
out.println "import ${basePackage}.domain.entity.*;"
out.println "import java.util.List;"
out.println "import org.springframework.data.domain.*;"
out.println "import org.springframework.beans.BeanUtils;"
out.println ""
out.println ""
out.println "/**\n" +
" * @Description \n" +
" * @Author Mu\n" + //
" * @Date " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \n" +
" */"
out.println ""
out.println "@Service"
out.println "public class ${entityName}ServiceImpl implements ${entityName}Service {"
out.println ""
out.println ""
out.println "\t@Autowired"
out.println "\tprivate ${entityName}Repository " + theFirstToLowerCase("${entityName}") + "repository;"
out.println ""
out.println ""
out.println "\t/**"
out.println "\t* queryAll"
out.println "\t* @return List<${entityName}Resp>"
out.println "\t*/"
out.println "\t@SneakyThrows"
out.println "\t@Override"
out.println "\t public List<${entityName}Resp> queryAll(){"
out.println "\t List<${entityName}> list =" + theFirstToLowerCase("${entityName}") + "repository.findAll();"
out.println "\t if (!list.isEmpty()) {"
out.println "\t List< ${entityName}Resp> respList = newBean(list, List.class); "
out.println "\t return respList; "
out.println "\t}"
out.println "\t return null; "
out.println "\t}"
out.println ""
out.println "\t/**"
out.println "\t* findById"
out.println "\t* @param id"
out.println " \t* @return ${entityName}Resp"
out.println "\t*/"
out.println "\t@SneakyThrows"
out.println "\t@Override"
out.println "\t public ${entityName}Resp findById(long id){"
out.println "\t Optional<${entityName}> byId = " + theFirstToLowerCase("${entityName}") + "repository.findById(id);"
out.println "\t if (byId.isPresent()) {"
out.println "\t ${entityName}Resp entity = newBean(byId.get(), ${entityName}Resp.class); "
out.println "\t return entity; "
out.println "\t}"
out.println "\t return null; "
out.println "\t}"
out.println ""
out.println "\t/**"
out.println "\t* create"
out.println "\t* @param resources"
out.println "\t*/"
out.println "\t@SneakyThrows"
out.println "\t@Override"
out.println "\t public void create(${entityName}Req resources){"
out.println "\t ${entityName} entity = newBean(resources, ${entityName}.class); "
out.println "\t " + theFirstToLowerCase("${entityName}") + "repository.save(entity);"
out.println "\t}"
out.println ""
out.println "\t/**"
out.println "\t* update"
out.println "\t* @param resources"
out.println "\t*/"
out.println "\t@SneakyThrows"
out.println "\t@Override"
out.println "\t public void update(${entityName}Req resources){"
out.println "\t Optional<${entityName}> byId = " + theFirstToLowerCase("${entityName}") + "repository.findById(resources.getId());"
out.println "\t if (byId.isPresent()) {"
out.println "\t ${entityName} entity = newBean(resources, ${entityName}.class); "
out.println "\t" + theFirstToLowerCase("${entityName}") + "repository.save(entity);"
out.println "\t}"
out.println "\t}"
out.println ""
out.println "\t/**"
out.println "\t* deleteById"
out.println "\t* @param id"
out.println "\t*/"
out.println "\t@SneakyThrows"
out.println "\t@Override"
out.println "\tpublic void deleteById(long id){"
out.println "\t Optional<${entityName}> byId = " + theFirstToLowerCase("${entityName}") + "repository.findById(id);"
out.println "\t if (byId.isPresent()) "
out.println "\t " + theFirstToLowerCase("${entityName}") + "repository.deleteById(id);"
out.println "\t}"
out.println ""
out.println "\t/**"
out.println "\t* listOfPage"
out.println "\t* @param pageSize "
out.println "\t* @param pageNumber"
out.println "\t* @return Page<${entityName}>"
out.println "\t*/"
out.println "\t@SneakyThrows"
out.println "\t@Override"
out.println "\t public Page<${entityName}> listOfPage(int pageSize, int pageNumber){"
out.println "\tPageRequest page = PageRequest.of(pageNumber - 1, pageSize, Sort.by( \"op_time\").descending());"
out.println "\t Page<${entityName}> pageList =" + theFirstToLowerCase("${entityName}") + "repository.findAll(page);"
out.println "\t return pageList; "
out.println "\t}"
out.println ""
out.println "\t@SneakyThrows"
out.println "\t private static <U, V> U newBean(V source, Class<U> targetClass) {"
out.println "\t U target = targetClass.newInstance();"
out.println "\t BeanUtils.copyProperties(source, target);"
out.println "\t return target;"
out.println "\t}"
out.println "}"
}
// 生成文件夹
def mkdirs(dirs) {
dirs.forEach {
def f = new File(it)
if (!f.exists()) {
f.mkdirs()
}
}
}
def clacBasePackage(dir) {
dir.toString()
.replaceAll("^.+\\\\src\\\\main\\\\java\\\\", "")
.replaceAll("\\\\", ".")
}
def isBaseEntityProperty(property) {
baseEntityProperties.find { it == property } != null
}
// 转换类型
def calcFields(table) {
DasUtil.getColumns(table).reduce([]) { fields, col ->
def spec = Case.LOWER.apply(col.getDataType().getSpecification())
def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
fields += [[
name : javaName(col.getName(), false),
colum : col.getName(),
type : typeStr,
dataType : col.getDataType().toString().replaceAll(/\(.*\)/, "").toLowerCase(),
len : col.getDataType().toString().replaceAll(/[^\d]/, ""),
default : col.getDefault(),
comment : col.getComment(),
isNotNull: col.isNotNull(),
position : col.getPosition(),
// getDefault : col.getDefault(),
// getParent : col.getParent(),
// getTable : col.getTable(),
// getDataType : col.getDataType(),
// isNotNull : col.isNotNull(),
// getWeight : col.getWeight(),
// getDocumentation : col.getDocumentation(),
// getTableName : col.getTableName(),
// getName : col.getName(),
// getLanguage : col.getLanguage(),
// getTypeName : col.getTypeName(),
// isDirectory : col.isDirectory(),
// isValid : col.isValid(),
// getComment : col.getComment(),
// getText : col.getText(),
// getDeclaration : col.getDeclaration(),
// getPosition : col.getPosition(),
// canNavigate : col.canNavigate(),
// isWritable : col.isWritable(),
// getIcon : col.getIcon(),
// getManager : col.getManager(),
// getDelegate : col.getDelegate(),
// getChildren : col.getChildren(),
// getKind : col.getKind(),
// isCaseSensitive : col.isCaseSensitive(),
// getProject : col.getProject(),
// getDataSource : col.getDataSource(),
// getVirtualFile : col.getVirtualFile(),
// getMetaData : col.getMetaData(),
// canNavigateToSource : col.canNavigateToSource(),
// getDisplayOrder : col.getDisplayOrder(),
// getDasParent : col.getDasParent(),
// getLocationString : col.getLocationString(),
// getDependences : col.getDependences(),
// getBaseIcon : col.getBaseIcon(),
// getNode : col.getNode(),
// getTextLength : col.getTextLength(),
// getFirstChild : col.getFirstChild(),
// getLastChild : col.getLastChild(),
// getNextSibling : col.getNextSibling(),
// getTextOffset : col.getTextOffset(),
// getPrevSibling : col.getPrevSibling(),
// getPresentation : col.getPresentation(),
// isPhysical : col.isPhysical(),
// getTextRange : col.getTextRange(),
// getPresentableText : col.getPresentableText(),
// textToCharArray : col.textToCharArray(),
// getStartOffsetInParent: col.getStartOffsetInParent(),
// getContext : col.getContext(),
// getUseScope : col.getUseScope(),
// getResolveScope : col.getResolveScope(),
// getReferences : col.getReferences(),
// getReference : col.getReference(),
// getContainingFile : col.getContainingFile(),
// getOriginalElement : col.getOriginalElement(),
// getNavigationElement : col.getNavigationElement(),
// getUserDataString : col.getUserDataString(),
// isUserDataEmpty : col.isUserDataEmpty(),
// getDbParent : col.getDbParent(),
]]
}
}
def javaName(str, capitalize) {
def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }
.join("").replaceAll(/[^\p{javaJavaIdentifierPart}]/, "_").replaceAll(/_/, "").minus("Tb")
capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
选择你需要生成的全部表
– 替换文件保持之后
根据图片中的步骤执行脚本
选择你的项目路径,进行生成相对的java文件;
–脚本中的BaseController
–BaseController中的DemoException .class是项目中自定义异常根据项目需求自己定义
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ValidationException;
@ControllerAdvice
public class BaseController {
private static final Logger log = LoggerFactory.getLogger(BaseController.class);
@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
@ResponseBody
public Response exception(HttpRequestMethodNotSupportedException e) {
log.info("Method Error={}", e.getMessage());
return Response.error(ErrorObject.unimplemented("不支持 " + e.getMethod() + " 请求"));
}
@ExceptionHandler(value = HttpMessageNotReadableException.class)
@ResponseBody
public Response exception(HttpMessageNotReadableException e) {
log.info("Argument Error={}", e.getMessage());
return Response.error(ErrorObject.invalidArgument("请求参数不能为空"));
}
@ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseBody
public Response exception(MethodArgumentNotValidException e) {
// e.printStackTrace();
BindingResult result = e.getBindingResult();
String msg = "";
if (result.hasErrors()) {
msg = result.getFieldErrors().get(0).getDefaultMessage();
}
log.info("argument error: {}", e.getMessage());
log.debug("fail: {}", Response.error(ErrorObject.invalidArgument(msg)));
return Response.error(ErrorObject.invalidArgument(msg));
}
@ExceptionHandler(value = ValidationException.class)
@ResponseBody
public Response exception(ValidationException e) {
log.info("argument error={}", e.getMessage());
String[] msg = e.getMessage().split(":");
log.debug("fail: {}", Response.error(ErrorObject.invalidArgument(msg[msg.length - 1].trim())));
return Response.error(ErrorObject.invalidArgument(msg[msg.length - 1].trim()));
}
@ExceptionHandler(value = MissingRequestHeaderException.class)
@ResponseBody
public Response exception(MissingRequestHeaderException e) {
log.info("header error={}", e.getMessage());
log.debug("fail: {}", Response.error(ErrorObject.invalidArgument(e.getHeaderName() + " 头信息不能为空")));
return Response.error(ErrorObject.invalidArgument(e.getHeaderName() + " 头信息不能为空"));
}
@ExceptionHandler(value = DemoException .class)
@ResponseBody
public Response exception(HttpServletRequest request, HttpServletResponse response, MyException e) {
log.info("business error={}", ((MyException) e).getMessage());
log.debug("fail: {}", Response.error(((MyException) e).getError()));
return Response.error(((MyException) e).getError());
}
@ExceptionHandler
@ResponseBody
public Response exception(Exception e) {
log.info("system error={}", e.getMessage());
log.debug("fail: {}", Response.error(ErrorObject.unknown("未知错误")));
return Response.error(ErrorObject.unknown("未知错误"));
}
@ExceptionHandler(value = HttpMediaTypeNotSupportedException.class)
@ResponseBody
public Response exception(HttpMediaTypeNotSupportedException e) {
log.info("body error={}", e.getMessage());
log.debug("fail: {}", Response.error(ErrorObject.invalidArgument(e.getMessage())));
return Response.error(ErrorObject.invalidArgument("请求不支持该参数格式"));
}
}
–DemoException
public class DemoException extends Exception {
private ErrorObject error;
public ErrorObject getError() {
return error;
}
public void setError(ErrorObject error) {
this.error = error;
}
public DemoException (ErrorObject error, String msg) {
super(msg);
this.error = error;
}
public DemoException (String msg) {
super(msg);
}
public void setMessage(String msg) {
if (null != error) {
error.setMessage(msg);
}
}
– 可以修改脚本中的返回体,改成自己需要的返回体
脚本中的返回体
@JsonInclude(JsonInclude.Include.NON_NULL)
@Schema(name = "Response", description = "返回体")
public class Response<T> {
@Schema(name = "error", description = "返回错误信息(错误码,错误信息)")
private ErrorObject error;
@Schema(name = "data", description = "返回业务数据")
T data;
@Schema(name = "pageable", description = "返回分页数据", required = false)
PageResp pageable;
public PageResp getPageable() {
return pageable;
}
public void setPageable(PageResp pageable) {
this.pageable = pageable;
}
@SuppressWarnings("all")
public static Response success() {
Response r = new Response();
r.setError(ErrorObject.success("OK"));
return r;
}
@SuppressWarnings("all")
public static <T> Response success(T data) {
Response r = new Response<>();
r.setError(ErrorObject.success("OK"));
r.setData(data);
return r;
}
@SuppressWarnings("all")
public static <T> Response success(PageResp pageable, T data) {
Response r = new Response<>();
r.setError(ErrorObject.success("OK"));
r.setPageable(pageable);
r.setData(data);
return r;
}
@SuppressWarnings("all")
public static Response error(ErrorObject error) {
Response r = new Response();
r.error = error;
return r;
}
public ErrorObject getError() {
return error;
}
public void setError(ErrorObject error) {
this.error = error;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "Response [data=" + data + ", error=" + error + "]";
}
public static <T> Response success(String msg, T data) {
Response r = new Response<>();
r.setError(ErrorObject.success(msg));
r.setData(data);
return r;
}
}
@Schema(description = "分页信息实体对象,非必须字段,查询列表接口使用")
public class PageResp {
/**
* 每页显示数量
*/
@Schema(description = "每页大小", minimum = "1", defaultValue = "10", example = "10")
@JsonProperty("page_size")
private Integer pageSize;
/**
* 当前页面
*/
@Schema(description = "当前第几页", minimum = "1", defaultValue = "1", example = "1")
@JsonProperty("page_number")
private Integer pageNumber;
/**
* 总页面数量
*/
@Schema(description = "总共页数", minimum = "1", example = "7")
@JsonProperty("total_pages")
private Integer totalPages;
/**
* 总共条数
*/
@Schema(description = "总共条数", minimum = "1", example = "66")
private Long total;
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getPageNumber() {
return pageNumber;
}
public void setPageNumber(Integer pageNumber) {
this.pageNumber = pageNumber;
}
public Integer getTotalPages() {
return totalPages;
}
public void setTotalPages(Integer totalPages) {
this.totalPages = totalPages;
}
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
}
public class ErrorObject {
Integer code;
String message;
public ErrorObject(Integer code, String message) {
this.code = code;
this.message = message;
}
public ErrorObject() {
}
public static ErrorObject success(String m) {
return new ErrorObject(ErrorCode.SUCCESS.ordinal(), m);
}
public static ErrorObject invalidArgument(String m) {
return new ErrorObject(ErrorCode.INVALID_ARGUMENT.ordinal(), m);
}
public static ErrorObject notFound(String m) {
return new ErrorObject(ErrorCode.NOT_FOUND.ordinal(), m);
}
public static ErrorObject permissionDenied(String m) {
return new ErrorObject(ErrorCode.PERMISSION_DENIED.ordinal(), m);
}
public static ErrorObject alreadyExists(String m) {
return new ErrorObject(ErrorCode.ALREADYEXISTS.ordinal(), m);
}
public static ErrorObject unauthenicated(String m) {
return new ErrorObject(ErrorCode.UNAUTHENTICATED.ordinal(), m);
}
//THIRD_PARTY_SERVICE_ERROR
public static ErrorObject thirddPaRtyServiceError(String msg) {
return new ErrorObject(8, msg);
}
public static ErrorObject unimplemented(String m) {
return new ErrorObject(ErrorCode.UNIMPLEMENTED.ordinal(), m);
}
public static ErrorObject unknown(String msg) {
return new ErrorObject(ErrorCode.UNKNOWN.ordinal(), msg);
}
@Override
public String toString() {
return "ErrorObject [code=" + code + ", message=" + message + "]";
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public class ErrorObject {
Integer code;
String message;
public ErrorObject(Integer code, String message) {
this.code = code;
this.message = message;
}
public ErrorObject() {
}
public static ErrorObject success(String m) {
return new ErrorObject(ErrorCode.SUCCESS.ordinal(), m);
}
public static ErrorObject invalidArgument(String m) {
return new ErrorObject(ErrorCode.INVALID_ARGUMENT.ordinal(), m);
}
public static ErrorObject notFound(String m) {
return new ErrorObject(ErrorCode.NOT_FOUND.ordinal(), m);
}
public static ErrorObject permissionDenied(String m) {
return new ErrorObject(ErrorCode.PERMISSION_DENIED.ordinal(), m);
}
public static ErrorObject alreadyExists(String m) {
return new ErrorObject(ErrorCode.ALREADYEXISTS.ordinal(), m);
}
public static ErrorObject unauthenicated(String m) {
return new ErrorObject(ErrorCode.UNAUTHENTICATED.ordinal(), m);
}
//THIRD_PARTY_SERVICE_ERROR
public static ErrorObject thirddPaRtyServiceError(String msg) {
return new ErrorObject(8, msg);
}
public static ErrorObject unimplemented(String m) {
return new ErrorObject(ErrorCode.UNIMPLEMENTED.ordinal(), m);
}
public static ErrorObject unknown(String msg) {
return new ErrorObject(ErrorCode.UNKNOWN.ordinal(), msg);
}
@Override
public String toString() {
return "ErrorObject [code=" + code + ", message=" + message + "]";
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
public enum ErrorCode {
SUCCESS("success"), INVALID_ARGUMENT("invalid_argument"), PERMISSION_DENIED("permission_denied"),
NOT_FOUND("not_found"), ALREADYEXISTS("ALREADYEXISTS"), UNAUTHENTICATED("unauthenticated"), UNKNOWN("unknown"),
UNIMPLEMENTED("unimplemented");
private String msg = "";
private ErrorCode(String msg) {
this.msg = msg;
}
public String getMsg() {
return this.msg;
}
}
**--脚本中的模板生成的单表的CURD就可以正常运行了**
**PS:idea的使用费用,慈禧老佛爷已经替我们付过了!**