Generate POJOs.groovy

简介: Generate POJOs.groovy
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
packageName = ""
typeMapping = [
        (~/(?i)tinyint|smallint|mediumint/)      : "BigDecimal",
        (~/(?i)bool|bit/)                        : "BigDecimal",
        (~/(?i)int/)                             : "BigDecimal",
        (~/(?i)float|double|decimal|real|number/): "BigDecimal",
        (~/(?i)datetime|timestamp/)              : "Date",
        (~/(?i)date/)                            : "Date",
        (~/(?i)time/)                            : "Date",
        (~/(?i)/)                                : "String",
        (~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream"
]
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)
    packageName = getPackageName(dir)
    new File(dir, className + ".java").withPrintWriter("utf-8") { out -> generate(out, className, table, fields) }
}
def generate(out, className, table, fields) {
    Set<String> types = new HashSet<String>()
    fields.each() {
        types.add(it.type)
    }
    out.println "package $packageName"
    out.println ""
    out.println "import org.hibernate.annotations.GenericGenerator;"
    out.println "import lombok.Data;"
    out.println "import javax.persistence.*;"
    out.println ""
    if (types.contains("Date") || types.contains("timestamp")) {
        out.println "import java.util.Date;"
        out.println "import com.fasterxml.jackson.annotation.JsonFormat;"
    }
    if (types.contains("InputStream")) {
        out.println "import java.io.InputStream;"
    }
    if (types.contains("BigDecimal")) {
        out.println "import java.math.BigDecimal;"
    }
    out.println ""
    out.println "/**\n" +
            " * @Author hanshuhao \n" +
            " * @description $className \n" +
            " **/"
    out.println "@Data"
    out.println "@Entity"
    out.println "@Table(name = \"" + table.getName() + "\")"
    out.println "public class $className {"
    out.println "    private static final long serialVersionUID = 1734425407533156215L;"
    fields.each() {
        out.println ""
        if (isNotEmpty(it.comment)) {
            out.println "\t/**"
            out.println "\t * ${it.comment.toString()}"
            out.println "\t */"
        }
        if (it.name.toUpperCase().equals("ID")) {
            out.println "    @Id"
            out.println "    @GeneratedValue(generator = \"uuidGenerator\")"
            out.println "    @GenericGenerator(name = \"uuidGenerator\", strategy = \"uuid\")"
        }
        out.println "    @Column(name = \"${it.column}\")"
        if (it.type.toLowerCase().contains("date") || it.type.toLowerCase().contains("timestamp")) {
            out.println "    @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")"
        }
        if (it.annos != "") out.println "  ${it.annos}"
//    if (it.comment != "")  out.println "  /*** ${it.comment} */"
        out.println "    private ${it.type} ${it.name};"
    }
    out.println "}"
}
def getPackageName(dir) {
    return dir.toString().replaceAll("\\\\", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}
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 += [[
                           column : col.getName(),
                           comment: col.getComment(),
                           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]
}
def isNotEmpty(content) {
    return content != null && content.toString().trim().length() > 0
}
相关文章
|
3月前
|
Python
【Python】解决Can‘t find model ‘en‘. It doesn‘t seem to be a shortcut link, a Python package or a valid
在使用以下代码时,报错Can’t find model ‘en’. It doesn’t seem to be a shortcut link, a Python package or a valid path to a data directory.
55 1
|
6月前
|
算法 项目管理 开发者
【Conan 入门教程 】深入解析Conan中的依赖关系的定义方法(In-depth Analysis of Dependency Definition Methods in Conan)
【Conan 入门教程 】深入解析Conan中的依赖关系的定义方法(In-depth Analysis of Dependency Definition Methods in Conan)
262 0
|
C++
VS Code注释插件doxygen documentation generator
VS Code注释插件doxygen documentation generator
744 0
VS Code注释插件doxygen documentation generator
|
Android开发 Kotlin
kotlin协程库报错“Program type already present”解决
最近在学习kotlin,学习到协程库这一块了,针对Android的话就是coroutines-android库。本来学习就不容易了,再加上kotlin现在还处于快速变化期,那个酸爽简直了,废话不多说,进入正题。
|
存储 安全 API
Objective-C Runtime 基本使用
在上一篇文章Objective-C Runtime详解 中我们探讨了Runtime的基本原理,这篇文章我们将总结一下Runtime的一些基本使用
199 0
|
IDE Java 开发工具
IDE gradle 同步报错 IDE gradle 同步报错 Unable to find method ''org.gradle.api.tasks.TaskInputs org.gradle.api.tasks.TaskInputs.file
IDE gradle 同步报错 IDE gradle 同步报错 Unable to find method ''org.gradle.api.tasks.TaskInputs org.gradle.api.tasks.TaskInputs.file
994 0
|
测试技术
【错误记录】IntelliJ IDEA 编译 Groovy 报错 ( GroovyRuntimeException: This script or class could not be run. )
【错误记录】IntelliJ IDEA 编译 Groovy 报错 ( GroovyRuntimeException: This script or class could not be run. )
417 0
【错误记录】IntelliJ IDEA 编译 Groovy 报错 ( GroovyRuntimeException: This script or class could not be run. )
|
Android开发 Kotlin
【错误记录】Android Studio 编译时 Kotlin 代码编译报错 ( Not enough information to infer type variable T )
【错误记录】Android Studio 编译时 Kotlin 代码编译报错 ( Not enough information to infer type variable T )
249 0
|
Java Apache Maven
mybatis-generator运行报错Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.5:generate (default-cli) on project testone: Exec
"C:Program FilesJavajdk-9.0.4binjava.exe" -Dmaven.multiModuleProjectDirectory=E:testone "-Dmaven.home=D:IDEAIntelliJ IDEA 2018.
16224 0
Travis CI Could not find or load main class org.gradle.wrapper.GradleWrapperMain 错误
问题 在 Travis CI 编译的时候出现 Error: Could not find or load main class org.gradle.wrapper.GradleWrapperMain 错误。
1522 0