Kotlin)Intellij entity 자동생성 방법

💦💦💦💦·2023년 2월 8일
0

kotlin

목록 보기
2/2

200개 넘어가는 table을 생성해야 한다

Intllij 에서 편리하게 생성이 가능하다
데이터베이스 : Mysql

1.DataGrip 으로 DB 연결(접속) 하기

2.접속후 화면

3.Generate POJOs.groovy 파일 위치 이동

4.Generate POJOs 코드를 조금 수정했다

gist 이동

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

import javax.swing.JFrame
import javax.swing.JOptionPane

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

typeMapping = [
        (~/(?i)bigint/)                   : "Long",
        (~/(?i)int/)                      : "Long",
        (~/(?i)float|double|decimal|real/): "Double",
        (~/(?i)numeric/)                  : "BigDecimal",
        (~/(?i)varchar/)                  : "String",
        (~/(?i)char/)                     : "String",
        (~/(?i)datetime|timestamp/)       : "LocalDateTime",
        (~/(?i)date/)                     : "java.sql.Date",
        (~/(?i)time/)                     : "java.sql.Time",
        (~/(?i)/)                         : "String"
]

def input = {
    JFrame jframe = new JFrame()
    String answer = JOptionPane.showInputDialog(jframe, it)
    jframe.dispose()
    answer
}
packageName = input("Enter your package name")

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

def generate(out, tableName, className, fields) {
    out.println "package $packageName"
    out.println ""
    out.println "import jakarta.persistence.Entity"
    out.println "import jakarta.persistence.Id"
    out.println "import jakarta.persistence.Table"
    out.println "import jakarta.persistence.Column"
    out.println "import java.time.LocalDateTime"
    out.println ""
    out.println "@Entity"
    out.println "@Table(name = \"$tableName\")"
    out.println "class ${className}("
    out.println "    @Id"
    fields.each() {
        if (it.annos != "") {
            out.println "  ${it.annos}"
        }

        if (it.type == "Int") {
            out.println "    @Column(name = \"${it.colName}\")"
            out.println "    val ${it.name}: ${it.type}? = 0,"
        } else if (it.type == "Boolean") {
            out.println "    @Column(name = \"${it.colName}\")"
            out.println "    val ${it.name}: ${it.type} = false,"
        } else if (it.type == 'varchar') {
            out.println "    @Column(name = \"${it.colName}\")"
            out.println "    val String ${it.name},"
        } else {
            out.println "    @Column(name = \"${it.colName}\")"
            out.println "    val ${it.name}: ${it.type}? = null,"
        }
        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 += [[
                           colName: col.getName(),
                           name : javaName(col.getName(), false),
                           type : typeStr,
                           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]
}

5. Entity 생성하기 (스크립트 실행실행)

데이터베이스나, 테이블에서 우클릭후 실행하면 된다

6. Entity 저장위치 선택 (파일이 생성됨)

profile
속도보다 방향

0개의 댓글