groovy 自动生成entity、mapper/service类代码

  • Post author:
  • Post category:其他


本文主要讲述如何通过idea 的script 插件 自动生成 entity、mapper/serivice 等一写简单类。减少低质量的工作任务,提高工作效率。



创建数据库连接

在这里插入图片描述

在这里插入图片描述



新增entity、mapper、serivce 类自动生成代码的groovy 脚本文件

下面我已 生成实体类的脚本为例,大家可以根据自己的实际情况,进行修改



主要关注点

  1. java 类创建人基本信息 在 87~91 行
  2. 需要引入的注解。 在93~ 103 行
  3. 实体类是否要保留表名的统一前缀 175 行
  4. 实体类后缀 在第36 行 className = className+‘Entity’
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.io.*
import java.text.SimpleDateFormat

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */
packageName = ""
typeMapping = [
		// bigint 在int 前面 或者 会被int 优先适配
		(~/(?i)bigint/)                          : "Long",
        (~/(?i)tinyint|smallint|mediumint|int/)  : "Integer",
        (~/(?i)bool|bit/)                        : "Boolean",
        (~/(?i)float|double|decimal|real/)       : "Double",
        (~/(?i)datetime|timestamp/)              : "LocalDateTime",
        (~/(?i)date/)                            : "LocalDateTime",
        (~/(?i)time/)                            : "LocalDateTime",
        (~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream",
        (~/(?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 className = javaClassName(table.getName(), true)
  def className = javaName(table.getName(), true)
  className = className+'Entity'
  def fields = calcFields(table)
  packageName = getPackageName(dir)
  PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "UTF-8"))
  printWriter.withPrintWriter {out -> generate(out, className, fields,table)}

//    new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields,table) }
}

// 获取包所在文件夹路径
def getPackageName(dir) {
  return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}

def generate(out, className, fields,table) {
  def tableName = table.getName()
  out.println "package $packageName"
  out.println ""
//  out.println "import javax.persistence.Column;"
//  out.println "import javax.persistence.Entity;"
//  out.println "import javax.persistence.Table;"
  out.println "import java.io.Serializable;"
//  out.println "import com.fasterxml.jackson.annotation.JsonIgnoreProperties;"
  out.println "import com.fasterxml.jackson.annotation.JsonInclude;"
  out.println "import lombok.NoArgsConstructor;"
  out.println "import lombok.EqualsAndHashCode;"
  out.println "import lombok.Getter;"
  out.println "import lombok.Setter;"
  out.println "import lombok.ToString;"
  out.println "import com.baomidou.mybatisplus.annotation.TableName;"

  Set types = new HashSet()

  fields.each() {
    types.add(it.type)
  }

  if (types.contains("LocalDateTime")) {
    out.println "import java.time.LocalDateTime;"
  }

  if (types.contains("LocalDate")) {
    out.println "import java.time.LocalDate;"
  }
  if (types.contains("LocalTime")) {
    out.println "import java.time.LocalTime;"
  }
  if (types.contains("InputStream")) {
    out.println "import java.io.InputStream;"
  }
  out.println ""
  out.println "/**\n" +
          " * @Description  \n" +
          " * @Author  songxulu@pxjy.com \n" +
          " * @Date "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
          " */"
  out.println ""
  out.println "@Getter"
  out.println "@Setter"
  out.println "@ToString"
  out.println "@NoArgsConstructor"
  out.println "@EqualsAndHashCode"
//  out.println "@JsonInclude(JsonInclude.Include.NON_NULL)"
//  out.println "@JsonIgnoreProperties(value = {\"hibernateLazyInitializer\", \"handler\", \"fieldHandler\"}, ignoreUnknown = true)"
//  out.println "@Entity"
  out.println "@TableName(\""+table.getName() +"\")"
  out.println "public class $className  extends BaseEntity implements Serializable {"
  out.println genSerialID()


  // 判断自增
  if ((tableName + "_id").equalsIgnoreCase(fields[0].colum) || "id".equalsIgnoreCase(fields[0].colum)) {
    out.println "\t@Id"
  }


  fields.each() {

    if ("createBy".equals(it.name) || "createByTime".equals(it.name) ||
            "lastModifiedByTime".equals(it.name) || "lastModifiedBy".equals(it.name)) {
      return
    }

    out.println ""
    // 输出注释
    if (isNotEmpty(it.commoent)) {
      out.println "\t/**"
      out.println "\t * ${it.commoent.toString()}"
      out.println "\t */"
    }

    if (it.annos != "") out.println "   ${it.annos.replace("[@Id]", "")}"

    // 输出成员变量
    out.println "\tprivate ${it.type} ${it.name};"
  }

  // 输出get/set方法
  /*fields.each() {
    out.println ""
    out.println "\tpublic ${it.type} get${it.name.capitalize()}() {"
    out.println "\t\treturn this.${it.name};"
    out.println "\t}"
    out.println ""

    out.println "\tpublic void set${it.name.capitalize()}(${it.type} ${it.name}) {"
    out.println "\t\tthis.${it.name} = ${it.name};"
    out.println "\t}"
  }*/
  out.println ""
  out.println "}"
}

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
    def comm =[
            colName : col.getName(),
            name :  javaName(col.getName(), false),
            type : typeStr,
            commoent: col.getComment(),
//            annos: "\t@Column(name = \""+col.getName()+"\" )",
            annos: ""
    ]
    if("id".equals(Case.LOWER.apply(col.getName())))
      comm.annos +=["@Id"]
    fields += [comm]
  }
}

// 处理类名(这里是因为我的表都是以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.htm
  s = 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}[_]]/, "_")
   if (str.startsWith("live"))
     s = s[4..s.size() - 1]
   else if(str.startsWith("px"))
     s = s[2..s.size() - 1]
	 
  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 str

  if(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('')
  }
}

static String genSerialID()
{
  return "\r\n\tprivate static final long serialVersionUID =  "+Math.abs(new Random().nextLong())+"L;"
}

以上内容复制到本地并修改完成后保存为以.groovy为后缀的文件。

并放置到 \config\extensions\com.intellij.database\schema 目录下



执行groovy 脚本

选择第一步增加的库找到需要操作的表。

右键–》scripted extensions–>generate xxxx.groovy(选择自己刚才新加的文件)

如果找不到,需要重启下idea

能后一步步按着提示操作就可以了。第一次使用,有可能会报以下错误,按照给的提示,一步步解决就行了。基本上都是一些语法错误。

在这里插入图片描述



mapper/service 等类的自动化生成

这个和实体类的流程是一致的,这里就不做重复性的描述了。只是脚本文件不一致。我在下面提供两个模板,大家自由参考。改进。



mapper.groovy

package src

import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "" // 需手动配置 生成的 dao 所在包位置

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
    def baseName = javaName(table.getName(), true)
	packageName = getPackageName(dir)
    new File(dir, baseName + "Mapper.java").withPrintWriter { out -> generateInterface(out, baseName) }
}

// 获取包所在文件夹路径
def getPackageName(dir) {
  return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}

def generateInterface(out, baseName) {
    def date = new Date().format("yyyy/MM/dd")
	out.println "package $packageName"
    out.println "import com.pxjy.live.entity.${baseName}Entity;" // 需手动配置
    out.println "import com.baomidou.mybatisplus.core.mapper.BaseMapper;"
    out.println "import org.apache.ibatis.annotations.Mapper;"
    out.println ""
    out.println "/**"
    out.println " * Created on $date."
    out.println " *"
    out.println " * @author songxulu@pxjy.com" // 可自定义
    out.println " */"
    out.println "@Mapper"
    out.println "public interface ${baseName}Mapper extends BaseMapper<${baseName}Entity> {" // 可自定义
    out.println ""
    out.println "}"
}

def javaName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
	if (str.startsWith("live"))
     s = s[4..s.size() - 1]
	else if(str.startsWith("px"))
     s = s[2..s.size() - 1]
	 
    name = capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}



service.groovy

package src

import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "" // 需手动配置 生成的 service 所在包位置

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
    def baseName = javaName(table.getName(), true)
	packageName = getPackageName(dir)
    new File(dir, baseName + "ServiceImpl.java").withPrintWriter { out -> generateFile(out, baseName) }
}

// 获取包所在文件夹路径
def getPackageName(dir) {
  return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}

def generateFile(out, baseName) {
	lbaseName = Case.LOWER.apply(baseName[0]) + baseName[1..-1]
    def date = new Date().format("yyyy/MM/dd")
	out.println "package $packageName"
	out.println ""
    out.println "import com.pxjy.live.mapper.${baseName}Mapper;" // 需手动配置
    out.println "import org.springframework.stereotype.Service;"
	out.println "import javax.annotation.Resource;"
	out.println ""
    out.println "/**"
    out.println " * Created on $date."
    out.println " *"
    out.println " * @author songxulu@pxjy.com" // 可自定义
    out.println " */"
    out.println ""
	out.println "@Service"
    out.println "public class ${baseName}ServiceImpl implements  ${baseName}Sevice{" // 可自定义
    out.println ""
	out.println "\t@Resourrce"
	out.println "\tprivate ${baseName}Mapper ${lbaseName}Mapper;"
    out.println "}"
}

def javaName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
	if (str.startsWith("live"))
     s = s[4..s.size() - 1]
    name = capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}



版权声明:本文为sessionsong原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。