一套可以生成pojo、service、service实现类、repository的Groovy模板
借鉴:子不语 / springBoot JPA代码生成器。根据自己项目需求改写而来。使用者可以根据自身需求修改代码。具体使用
1.IDEA中使用Database连接数据库如图所示:


3.选择GO To Scriptis Directory 复制本文中的代码 根据需求修改模板 粘贴在Generate POJOs.groovy中。
4.选中需要生成的数据表右键

5.选择文件生成的根目录

6.代码生成结束。放在对应的目录下运行项目即可。
import com.intellij.database.model.DasTableimport com.intellij.database.model.ObjectKindimport com.intellij.database.util.Caseimport com.intellij.database.util.DasUtilimport java.text.SimpleDateFormatconfig = [impSerializable : true,extendBasePojo : false,extendBaseService: true,useLombok : true, // 使用注解,不生成get、set方法ModelNotNULL : true, // 空值不返回注解ModelDate : true, // 日期类格式注解baseMethods : true, // ServiceImpl生成基础方法generateItem : ["Pojo","Service","ServiceImpl","Repository",]]basePojoProperties = ["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 pojoPath = "${dir.toString()}\\pojo",servicePath = "${dir.toString()}\\service",serviceImplPath = "${dir.toString()}\\service\\impl",repPath = "${dir.toString()}\\repository",controllerPath = "${dir.toString()}\\controller"mkdirs([pojoPath, servicePath,serviceImplPath, repPath, controllerPath])def pojoName = javaClassName(table.getName(), true)def fields = calcFields(table)def basePackage = getPackageName(dir)if (isGenerate("Pojo")) {genUTF8File(pojoPath, "${pojoName}.java").withPrintWriter { out -> genPojo(out, table, pojoName, fields, basePackage) }}if (isGenerate("Service")) {genUTF8File(servicePath, "${pojoName}Service.java").withPrintWriter { out -> genService(out, table, pojoName, fields, basePackage) }}if (isGenerate("ServiceImpl")) {genUTF8File(serviceImplPath, "${pojoName}ServiceImpl.java").withPrintWriter { out -> genServiceImpl(out, table, pojoName, fields, basePackage) }}if (isGenerate("Repository")) {genUTF8File(repPath, "${pojoName}Repository.java").withPrintWriter { out -> genRepository(out, table, pojoName, fields, basePackage) }}}// 获取包所在文件夹路径def getPackageName(dir) {return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ""}// 是否需要被生成def isGenerate(itemName) {config.generateItem.contains(itemName)}// 指定文件编码方式,防止中文注释乱码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}"out.println "\t */"// 默认表的第一个字段为主键if (field.position == 1) {out.println "\t@Id"}// 日期类加上注解if (field.dataType == "datetime" || field.dataType == "timestamp") {if (config.ModelDate) {out.println "\t@JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")"}}// 枚举不需要长度out.println "\t@Column(name = \"${field.colum}\", nullable = ${!field.isNotNull}${field.dataType == "enum" ?"": field.dataType == "datetime"||field.dataType == "timestamp" ? "" : ", length = $field.len"})"out.println "\tprivate ${field.type} ${field.name};"}// 生成实体类def genPojo(out, table, pojoName, fields, basePackage) {out.println "package ${basePackage}.pojo;"out.println ""if (config.extendBasePojo) {out.println "import $basePojoPackage;"}if (config.useLombok) {out.println "import lombok.Data;"out.println ""}if (config.impSerializable) {out.println "import java.io.Serializable;"out.println ""}out.println "import javax.persistence.*;"if (config.ModelNotNULL) {out.println "import com.fasterxml.jackson.annotation.JsonInclude;"}if (config.ModelDate) {out.println "import com.fasterxml.jackson.annotation.JsonFormat;"}out.println ""out.println "/**\n" +" * @Description: \n" +" * @Author: Kra\n" + //1. 修改idea为自己名字" * @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 $pojoName${config.extendBasePojo ? " extends BasePojo" : ""}${config.impSerializable ? " implements Serializable" : ""} {"if (config.extendBasePojo) {fields = fields.findAll { it ->!basePojoProperties.any { it1 -> it1 == it.name }}}fields.each() {genProperty(out, it)}if (!config.useLombok) {fields.each() {genGetSet(out, it)}}out.println "}"}// 生成Servicedef genService(out, table, pojoName, fields, basePackage) {out.println "package ${basePackage}.service;"out.println ""out.println "import ${basePackage}.pojo.$pojoName;"out.println ""out.println "/**\n" +" * @Description \n" +" * @Author Kra\n" + //1. 修改idea为自己名字" * @Date " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \n" +" */"out.println "public interface ${pojoName}Service${config.extendBaseService ? " extends BaseService<$pojoName, ${fields[0].type}>" : ""} {"out.println ""out.println "}"}// 生成ServiceImpldef genServiceImpl(out, table, pojoName, fields, basePackage) {out.println "package ${basePackage}.service.impl;"out.println ""out.println "import ${basePackage}.repository.${pojoName}Repository;"out.println "import ${basePackage}.service.${pojoName}Service;"out.println "import ${basePackage}.pojo.$pojoName;"if (config.baseMethods) {out.println "import java.util.List;"out.println "import org.springframework.transaction.annotation.Transactional;"out.println "import org.springframework.data.domain.*;"out.println "import java.util.Optional;"}out.println "import org.springframework.stereotype.Service;"out.println ""out.println "import javax.annotation.Resource;"out.println ""out.println "/**\n" +" * @Description \n" +" * @Author Kra\n" + //1. 修改idea为自己名字" * @Date " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \n" +" */"out.println "@Service"out.println "public class ${pojoName}ServiceImpl implements ${pojoName}Service {"out.println ""out.println "\t@Resource"out.println "\tprivate ${pojoName}Repository rep;"out.println ""out.println ""if (config.baseMethods) {//基础方法 saveout.println "\t public ${pojoName} save(${pojoName} obj) {"out.println "\t\t return rep.save(obj);"out.println "\t }"out.println ""out.println ""//基础方法 saveListout.println "\t @Transactional"out.println "\t public List<${pojoName}> saveAll(Iterable<${pojoName}> list) {"out.println "\t\t return rep.saveAll(list);"out.println "\t }"out.println ""out.println ""//基础方法 getOneout.println "\t public ${pojoName} getOne(${fields[0].type} id) {"out.println "\t\t return rep.getOne(id);"out.println "\t }"out.println ""out.println ""//基础方法 findByIdout.println "\t public ${pojoName} findById(${fields[0].type} id) {"out.println "\t\t Optional<${pojoName}> obj = rep.findById(id);"out.println "\t\t return obj.isPresent()?obj.get():null;"out.println "\t }"out.println ""out.println ""//基础方法 deleteByIdout.println "\t public void deleteById(${fields[0].type} id) {"out.println "\t\t rep.deleteById(id);"out.println "\t }"out.println ""out.println ""//基础方法 deleteAllout.println "\t @Transactional"out.println "\t public void deleteAll(List list) {"out.println "\t\t rep.deleteAll(list);"out.println "\t }"out.println ""out.println ""//基础方法 deleteout.println "\t public void delete(${pojoName} obj) {"out.println "\t\t rep.delete(obj);"out.println "\t }"out.println ""out.println ""//基础方法 existsByIdout.println "\t public boolean existsById(${fields[0].type} id) {"out.println "\t\t return rep.existsById(id);"out.println "\t }"out.println ""out.println ""//基础方法 countout.println "\t public long count() {"out.println "\t\t return rep.count();"out.println "\t }"out.println ""out.println ""//基础方法 findAllout.println "\t public List<${pojoName}> findAll() {"out.println "\t\t return rep.findAll();"out.println "\t }"out.println ""out.println ""//基础方法 findAllout.println "\t public List<${pojoName}> findAll(${pojoName} obj) {"out.println "\t\t List<${pojoName}> list = rep.findAll(Example.of(obj));"out.println "\t\t return list==null||list.size()<1?null:list;"out.println "\t }"out.println ""out.println ""//基础方法 findAllout.println "\t public List<${pojoName}> findAll(Sort sort) {"out.println "\t\t return rep.findAll(sort);"out.println "\t }"out.println ""out.println ""//基础方法 findAllByIdout.println "\t public List<${pojoName}> findAllById(Iterable<${fields[0].type}> ids) {"out.println "\t\t return rep.findAllById(ids);"out.println "\t }"out.println ""out.println ""//基础方法 findAllout.println "\t public List<${pojoName}> findAll(Example<${pojoName}> e) {"out.println "\t\t return rep.findAll(e);"out.println "\t }"out.println ""out.println ""//基础方法 findAllout.println "\t public List<${pojoName}> findAll(Example<${pojoName}> e, Sort sort) {"out.println "\t\t return rep.findAll(e,sort);"out.println "\t }"out.println ""out.println ""//基础方法 findAllout.println "\t public Page<${pojoName}> findAll(Pageable page) {"out.println "\t\t return rep.findAll(page);"out.println "\t }"out.println ""out.println ""//基础方法 findAllout.println "\t public Page<${pojoName}> findAll(Example<${pojoName}> e, Pageable page) {"out.println "\t\t return rep.findAll(e,page);"out.println "\t }"out.println ""out.println ""//基础方法 findAllout.println "\t public Page<${pojoName}> findAll(${pojoName} obj, Pageable page) {"out.println "\t\t return rep.findAll(Example.of(obj),page);"out.println "\t }"out.println ""out.println ""}out.println "}"}// 生成Repositorydef genRepository(out, table, pojoName, fields, basePackage) {out.println "package ${basePackage}.repository;"out.println ""out.println "import ${basePackage}.pojo.$pojoName;"out.println "import org.springframework.data.jpa.repository.JpaRepository;"out.println ""out.println "/**\n" +" * @Description \n" +" * @Author Kra\n" + //1. 修改idea为自己名字" * @Date " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \n" +" */"out.println "@Repository"out.println "public interface ${pojoName}Repository extends JpaRepository<$pojoName, ${fields[0].type}>{"out.println ""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 isBasePojoProperty(property) {basePojoProperties.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() }.valuefields += [[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(),]]}}// 这里是处理数据库表前缀的方法,这里处理的是t_xxx命名的表// 已经修改为使用javaName, 如果有需要可以在def className = javaName(table.getName(), true)中修改为javaClassName// 处理类名(这里是因为我的表都是以t_命名的,所以需要处理去掉生成类名时的开头的T,// 如果你不需要去掉表的前缀,那么请查找用到了 javaClassName这个方法的地方修改为 javaName 即可)def javaClassName(str, capitalize) {def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str).collect { Case.LOWER.apply(it).capitalize() }.join("").replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")// 去除开头的T http://developer.51cto.com/art/200906/129168.htms = s[1..s.size() - 1]capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]}def javaName(str, capitalize) {// def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }// .join("").replaceAll(/[^\p{javaJavaIdentifierPart}]/, "_")// capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str).collect { Case.LOWER.apply(it).capitalize() }.join("").replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]}def isNotEmpty(content) {return content != null && content.toString().trim().length() > 0}static String changeStyle(String str, boolean toCamel) {if (!str || str.size() <= 1)return strif (toCamel) {String r = str.toLowerCase().split('_').collect { cc -> Case.LOWER.apply(cc).capitalize() }.join('')return r[0].toLowerCase() + r[1..-1]} else {str = str[0].toLowerCase() + str[1..-1]return str.collect { cc -> ((char) cc).isUpperCase() ? '_' + cc.toLowerCase() : cc }.join('')}}//生成序列化的serialVersionUIDstatic String genSerialID() {return "\tprivate static final long serialVersionUID = " + Math.abs(new Random().nextLong()) + "L;"}
文章转载自精准丶优雅,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




