记录IDEA自动生成entity的groovy文件

记录使用IDEA自动生成entity的goovy文件。

  1. 带有数据库注释
  2. 已经修改int、date/datetiem/timestamp等数据格式
  3. 添加了lambda @Data注解
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

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

packageName = "com.iwhalecloud.mgtcenter.entity;"
typeMapping = [
  (~/(?i)int/)                      : "Integer",
  (~/(?i)float|double|decimal|real/): "double",
  (~/(?i)datetime|timestamp/)       : "Date",
  (~/(?i)date/)                     : "Date",
  (~/(?i)time/)                     : "java.sql.Time",
  (~/(?i)/)                         : "String"
]

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 className = javaName(table.getName(), true)
  def fields = calcFields(table)
  new File(dir, className + ".java").withPrintWriter("UTF-8") { out -> generate(out, className, fields) }
}

def generate(out, className, fields) {
  out.println "package $packageName"
  out.println ""
  out.println "import java.io.Serializable;"
  out.println "import lombok.Data;"
  Set types = new HashSet()

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

  if (types.contains("Date")) {
    out.println "import java.util.Date;"
  }

  if (types.contains("InputStream")) {
    out.println "import java.io.InputStream;"
  }
  out.println ""
  out.println "/**\n" +
          " * \n" +
          " * @author  byp\n" +
          " * @date "+ new Date().format("yyyy/MM/dd") + " \n" +
          " */"
  out.println "@Data"
  out.println "public class $className implements Serializable {"
  out.println ""
  out.println genSerialID()
  fields.each() {
    out.println ""
    // 输出注释
    if (isNotEmpty(it.comment)) {
      out.println "\t/**"
      out.println "\t * ${it.comment.toString()}"
      out.println "\t */"
    }
    if (it.annos != "") out.println "   ${it.annos.replace("[@Id]", "")}"
    // 输出成员变量
    out.println "\tprivate ${it.type} ${it.name};"
  }
  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
    fields += [[
                 name : javaName(col.getName(), false),
                 type : typeStr,
                 comment: col.getComment(),
                 annos: ""]]
  }
}

def javaName(str, capitalize) {
  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 genSerialID()
{
  return "\tprivate static final long serialVersionUID =  "+Math.abs(new Random().nextLong())+"L;"
}

 

你可能感兴趣的:(JAVA,学习总结,java)