IDEA database connection method to generate entity classes and generate custom Groovy script

Lead: now in 2019, there are many plug-ins or editors support the automatic generation of a data entity classes based on the data table, such as IDEA, a variety of MyBatis code generation tools, and so this introduction about how to use the IDEA. groovy script file to generate entity classes annotated with JPA

Reference Links: - sad autumn Intellij IDEA entity class annotated with detailed steps of generating a database tables

First, connect to the database using IDEA

  • It should be noted :
    1. The official version of IDEA have this feature, Community Edition wood
    2. IDEA demo version of the picture used was 2018.3, different versions of the interface may be small differences
  1. Create a new data connection
    • (1) If not, can the top menu bar: View - Open tool window -Database
    • New Oracle Database is the same operation

  1. Configuration data connection
    1. Fill a connection name, will do anything just to fill
    2. Do not choose, the default on the line
    3. Fill in the IP address of the database connection, such as local database can fill: localhost or 127.0.0.1
    4. Fill in the database open port number, if the default settings are generally not 3306
    5. Fill in the name of the database you want to connect
    6. Fill in the username database
    7. Fill in the password database
    8. There will be a driving need to click download, download the figure is already well
    9. Fill in your database connection url, then click the button located 9 test connections, check whether the local connection fails to open the mysql service

Second, the two kinds of IDEA's own method of creating an entity class

(1) If you just create a simple, only the property, getter, setter entity class, without the need for JPA / Hibernate entity class notes

1. 单击打开刚刚创建的数据连接
2. 打开schemas, 找到自己需要创建实体类的表(可以使用ctrl或shift多选)
3. 右键: Scripted Extensions - Generate POJOs.groovy
4. 选择生成路径就OK了
+ **需注意**
    + 生成的包名可能有问题, 默认是`package com.sample`, 需要自己手动修改

(2) using the Hibernate / Jpa frame is needed is annotated entity classes, Idea also provides a corresponding method

  • Add -1- module JPA
    1. Open the project structure
    2. Open the module, click the + sign to add module
    3. Select JPA
    4. Click the lower right corner OK to close the project structure

  • Persistence -2- tools used to generate the entity class annotated -1
    1. If you step on, then no problem, IDEA lower left corner of the sidebar toolbar appears Persistence
    2. Open Persistence toolbar, right-project: Generate Persistence Mapping - By Database Schema
  • Persistence -3- tools used to generate the entity class annotated -2
    1. Select the database connection
    2. Select package class is generated
    3. Select the table you want to generate
    4. Select the fields to be generated (upon addition to the default table field Select key)
    5. Modify the attribute name to be generated
    6. Modify the properties of the type to be generated
    7. That is generated on the hook annotated entity class
    Generating class instance as follows

Third, further, to use their own Groovy generate annotated entity classes

  1. The above describes two methods used to generate the entity classes IDEA, advantages and disadvantages
    + entity classes without generating annotated simple and efficient, but the disadvantage is that if you are using Jpa / Hibernate frame is not suitable
    + generated entity class can be annotated generate annotated entity classes, but the disadvantage is generated annotated entity classes may not meet our annotated, can only generate current project to the next bag, face a number of complex database systems such as Oracle will show a lot of tables and table space is not switched Convenience
  2. We know that Idea generates entity classes are not annotated by Groovy script file is generated, we can also find this file, then we can modify this file, it generates annotated entity classes it?

Benefits (1) use your own Groovy generate annotated entity classes

  1. In the Database toolbar, simple operation
  2. Can own some editing of the script, the generated entity classes to achieve their own custom needs
  3. Generating entity classes for the Oracle database such, to avoid the influence of system tables, can choose to operate the tablespace
  4. May be generated at any position on the computer, not limited

Less than (2) use your own Groovy generate annotated entity classes

  1. @author author needs to make changes to the script
  2. @Table (Schema = "") table space name can not be read, so you need to modify the script, set the table space name (mysql can delete the definition of this property) (IDEA The Persistence tools can read (Schema = "" attribute and generates, but we do not know how it was obtained)
  3. The primary key generated @Id unknown, the need to generate their own determination (mysql user can modify the script directly set the primary key generated, Oracle user needs to generate by-entity classes after confirmation)

(3) use your own Groovy generate annotated entity classes can continue to improve the place

1, if necessary hashcode () and equals () method, but also modify the script to automatically generate

(4) Create a Groovy script file

  1. Database toolbar, right-right: Scripted Extensions - Go to Scripts Directory
  2. Create a directory under Generate MyPOJOs.groovy

  1. Add the contents inside
    1. //1. 修改idea为自己名字 Where you can modify the author's name for their own
    2. //2. schema = \"后面添加自己的表空间名称(mysql可以不添加, 不用这个schema属性也行) Here you can modify the prompts
import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

import java.text.SimpleDateFormat

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */
packageName = ""
typeMapping = [
        (~/(?i)tinyint|smallint|mediumint/)      : "Integer",
        (~/(?i)int/)                             : "Long",
        (~/(?i)bool|bit/)                        : "Boolean",
        (~/(?i)float|double|decimal|real/)       : "Double",
        (~/(?i)datetime|timestamp|date|time/)    : "Date",
        (~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream",
        (~/(?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 className = javaName(table.getName(), true)
    def fields = calcFields(table)
    packageName = getPackageName(dir)
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "UTF-8"))
    printWriter.withPrintWriter { out -> generate(out, className, fields, table) }

//    new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields,table) }
}

// 获取包所在文件夹路径
def getPackageName(dir) {
    return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}

def generate(out, className, fields, table) {
    out.println "package $packageName"
    out.println ""
    out.println "import javax.persistence.Column;"
    out.println "import javax.persistence.Entity;"
    out.println "import javax.persistence.Table;"
    out.println "import javax.persistence.Id;"
    out.println "import javax.persistence.GeneratedValue;"
    out.println "import java.io.Serializable;"
    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" +
            " * @Description  \n" +
            " * @Author  idea\n" + //1. 修改idea为自己名字
            " * @Date " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
            " */"
    out.println ""
    out.println "@Entity"
    out.println "@Table ( name =\"" + table.getName() + "\" , schema = \"\")" //2. schema = \"后面添加自己的表空间名称(mysql可以不添加, 不用这个schema属性也行)
    out.println "public class $className  implements Serializable {"
    out.println ""
    out.println genSerialID()
    fields.each() {
        out.println ""
        // 输出注释
        if (isNotEmpty(it.commoent)) {
            out.println "\t/**"
            out.println "\t * ${it.commoent.toString()}"
            out.println "\t */"
        }

        if ((it.annos+"").indexOf("[@Id]") >= 0) out.println "\t@Id"

        if (it.annos != "") out.println "   ${it.annos.replace("[@Id]", "")}"


        // 输出成员变量
        out.println "\tprivate ${it.type} ${it.name};"
    }

    // 输出get/set方法
    fields.each() {
        out.println ""
        out.println "\tpublic ${it.type} get${it.name.capitalize()}() {"
        out.println "\t\treturn this.${it.name};"
        out.println "\t}"
        out.println ""

        out.println "\tpublic void set${it.name.capitalize()}(${it.type} ${it.name}) {"
        out.println "\t\tthis.${it.name} = ${it.name};"
        out.println "\t}"
    }

    // 输出toString方法
    out.println ""
    out.println "\t@Override"
    out.println "\tpublic String toString() {"
    out.println "\t\treturn \"TpApiConfig{\" +"
    fields.each() {
        out.println "\t\t\t\t\"${it.name}='\" + ${it.name} + '\\'' +"
    }
    out.println "\t\t\t\t'}';"
    out.println "\t}"

    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 comm = [
                colName : col.getName(),
                name    : javaName(col.getName(), false),
                type    : typeStr,
                commoent: col.getComment(),
                annos   : "\t@Column(name = \"" + col.getName() + "\" )"]
        if ("id".equals(Case.LOWER.apply(col.getName())))
            comm.annos += ["@Id"]
        fields += [comm]
    }
}

// 已经修改为使用javaName, 如果有需要可以在def className = javaName(table.getName(), true)中修改为javaClassName
// 处理类名(这里是因为我的表都是以t_命名的,所以需要处理去掉生成类名时的开头的T,
// 如果你不需要那么请查找用到了 javaClassName这个方法的地方修改为 javaName 即可)
def javaClassName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    // 去除开头的T  http://developer.51cto.com/art/200906/129168.htm
    s = s[1..s.size() - 1]
    capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

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

static String genSerialID() {
    return "\tprivate static final long serialVersionUID =  " + Math.abs(new Random().nextLong()) + "L;"
}

  1. Table on the right, choose to write their own scripts to generate entity classes
    effect is as follows:

Guess you like

Origin www.cnblogs.com/HF-lgy/p/11409728.html