自定义修改IDEA SpringJPA实体模板(第二版)

上篇已经提到了如何使用IDEA自带groovy脚本生成实体类了,这次又更新一些可能会用到的几个地方:

1.增加了生成Dao层接口(也可以指定生成Service类,可参考另一位大佬写的);
2.多个数据源下,可以指定到该包名下(multiplePackage);
3.可设置实体类继承一个公用的BaseEntity;
4.可设置实体类中@Column注解中的name一律小写;
脚本可参考:

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

config = [
        impSerializable  : true,
        extendBaseEntity : false,
        extendBaseService: true,
        extendBaseManager: true,

]

multiplePackage = "t"
baseEntityPackage = "com.tv189.util.response.BaseEntity"
baseServicePackage = "com.tv189.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 multipleDir  = "${dir.toString()}"
  def entityPath,repPath
  if (multiplePackage != ""){
     entityPath = "${multipleDir}/model/"+multiplePackage
        repPath = "${multipleDir}/manager/"+multiplePackage
  }else {
     entityPath = "${multipleDir}/model"
      repPath = "${multipleDir}/manager"
  }


  mkdirs([entityPath, repPath])

  def entityName = javaName(table.getName(), true)
  def fields = calcFields(table)
  def basePackage = clacBasePackage(dir)

  new File("${entityPath}/${entityName}.java").withPrintWriter { out -> genEntity(out, table, entityName, fields, basePackage) }
  //new File("${servicePath}\\${entityName}Service.java").withPrintWriter { out -> genService(out, table, entityName, fields, basePackage) }
  if (config.extendBaseManager){
    new File("${repPath}/${entityName}Manager.java").withPrintWriter { out -> genRepository(out, table, entityName, fields, basePackage) }
  }

}

def genProperty(out, field) {
  if (field.annos != "") out.println "  ${field.annos}"
  if (field.colum != field.name) {
    out.println "\t@Column(name = \"${field.colum}\")"
  }
  out.println "\tprivate ${field.type} ${field.name};"
  out.println ""
}

def genEntity(out, table, entityName, fields, basePackage) {
  if (multiplePackage != ""){
    out.println "package ${basePackage}.model.${multiplePackage};"
  }else{
    out.println "package ${basePackage}.model;"
  }
  out.println ""
  if (config.extendBaseEntity) {
    out.println "import $baseEntityPackage;"
  }
  out.println "import lombok.Data;"
  out.println ""
  if (config.impSerializable) {
    out.println "import java.io.Serializable;"
    out.println ""
  }
  out.println "import javax.persistence.*;"
  out.println ""
  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" : ""} {"
  out.println ""

  if ((entityName + "_id").equalsIgnoreCase(fields[0].colum) || "id".equalsIgnoreCase(fields[0].colum)) {
    out.println "\t@Id"
    out.println "\t@GeneratedValue(strategy=GenerationType.IDENTITY)"
  }

  fields.each() {
    if (it.annos != "") out.println "  ${it.annos}"
    out.println "\t@Column(name = \"${Case.LOWER.apply(it.colum)}\")"

    if (it.colum != it.name) {
      out.println "\tprivate ${it.type} ${it.colum};"
    }else {
      out.println "\tprivate ${it.type} ${it.name};"
    }
    out.println ""
  }

  out.println "}"

}

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}.entity.$entityName;"
  }
  out.println "import org.springframework.stereotype.Service;"
  out.println ""
  out.println "import javax.annotation.Resource;"
  out.println ""
  out.println "@Service"
  out.println "public class ${entityName}Service${config.extendBaseService ? " extends BaseService<$entityName, ${fields[0].type}>" : ""}  {"
  out.println ""
  out.println "\t@Resource"
  out.println "\tprivate ${entityName}Repository rep;"
  out.println "}"
}

def genRepository(out, table, entityName, fields, basePackage) {
  if (multiplePackage != ""){
    out.println "package ${basePackage}.manager.$multiplePackage;"
    out.println ""
    out.println "import ${basePackage}.model.$multiplePackage.$entityName;"
  }else{
    out.println "package ${basePackage}.manager;"
    out.println ""
    out.println "import ${basePackage}.model.$entityName;"
  }
  out.println "import org.springframework.data.jpa.repository.JpaRepository;"
  out.println "import org.springframework.data.jpa.repository.JpaSpecificationExecutor;"
  out.println ""
  out.println "public interface ${entityName}Manager extends JpaRepository<$entityName, ${fields[0].type}>, JpaSpecificationExecutor<${entityName}>{\r\r}"
}

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,
                         annos: ""]]
  }
}

def javaName(str, capitalize) {
  def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }
          .join("").replaceAll(/[^\p{javaJavaIdentifierPart}]/, "_").replaceAll(/_/, "")
  capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

需注意的地方

  • config中配置有是否要生成Dao和BaseEntity的开关;
  • 脚本中用的路径需要自己根据项目灵活配置;
  • 该脚本适用于mac环境,如果是windows用户需要修改一些文件路径的分隔符,windows下是(\),mac、linux下是(/)。
  • 第四点是可选的,我的项目中有这个问题存在所以自己配置了下,想使用驼峰形式则修改108行”${Case.LOWER.apply(it.colum)}>>it.colum“。

参考:

https://www.jianshu.com/p/523af440eaf6

你可能感兴趣的:(自定义修改IDEA SpringJPA实体模板(第二版))