idea根據數據庫表自動生成JPA實體類案例

在一些軟件開發過程模式下,可能會須要根據數據庫表生成對應的實體。在idea工具中如何作到這點呢?最簡單的答案多是使用插件吧。其實還有一個很快捷的方法,步驟以下:java

  1. 經過view->tool windows->database菜單,打開數據庫工具
  2. 鏈接數據庫
  3. 選定須要生成實體類的表,右鍵菜單選擇scripted extensions,有一個Generate POJOs.groovy

如今生成的實體類也許不能知足你的需求,你能夠本身寫一個groovy腳原本生成符合需求的實體類。在上面的第三步中,下面有一個go to scripts directory菜單,便可打開腳本目錄。在此目錄下新建一個腳本,好比Generate jpa Entity Object.groovy。sql

好比我建立的腳本以下數據庫

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 = "me.test.entity;"
typeMapping = [
        (~/(?i)bigint/)                   : "Long",
        (~/(?i)tinyint/)                  : "Boolean",
        (~/(?i)int/)                      : "Integer",
        (~/(?i)float|double|decimal|real/): "Double",
        (~/(?i)datetime|timestamp/)       : "java.sql.Timestamp",
        (~/(?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 }.each { generate(it, dir) }
}

def generate(table, dir) {
  def className = javaName(table.getName(), true)
  def fields = calcFields(table)
  new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields, table) }
}

def generate(out, className, fields, table) {
  out.println "package $packageName"
  out.println ""
  out.println "import lombok.Data;"
  out.println "import javax.persistence.*;"
  out.println ""
  out.println "/**"
  out.println " * entity class for ${table.getName()}"
  if (isNotEmpty(table.getComment())) {
    out.println " * ${table.getComment()}"
  }
  out.println "*/"
  out.println "@Data"
  out.println "@Entity"
  out.println "@Table(name = \"${table.getName()}\")"
  out.println "public class $className {"
  out.println ""
  fields.each() {
    out.println "\t/**"
    out.println "\t* ${isNotEmpty(it.comment) ? it.comment : it.name}"
    out.println "\t*/"
    if (it.annos.size() > 0)
      it.annos.each() {
        out.println "\t${it}"
      }
    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
    def anos = [];
    if (Case.LOWER.apply(col.getName()).equals('id')) {
      anos += ["@Id", "@GeneratedValue(strategy = GenerationType.IDENTITY)"]
    } else {
      anos += ["@Column(name = \"${col.getName()}\")"]
    }
    def field = [
            name : javaName(col.getName(), false),
            type : typeStr,
            comment: col.getComment(),
            annos: anos]
    fields += [field]
  }
}

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 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('')
  }
}
相關文章
相關標籤/搜索