转载  Spring Boot JPA实体类idea自动生成 其一

分类:websocket 2019-10-05T19:33:47    15人阅读   
转载于:https://www.jianshu.com/p/44bb7e25f5c7

  1. view -> Tool Windows -> Database
    image.png
  1. + -> Data source -> MySQL

  2. 配置数据库信息


    image.png
  3. 建立存放实体的包


    image.png
  4. 导入必要maven依赖

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>
        <!--jpa-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
  1. 在database视图区域任意地方右键,然后Scripted Extensions -> Go to Scripts Directory

    image.png

  2. 复制下面的文件到6中跳转的文件夹中

  • Generate POJOs.groovy
import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */
//修改为你的实体类的包名
packageName = "com.demo.jpa.entity;"
typeMapping = [
        (~/(?i)int/)                      : "Long",
        (~/(?i)float|double|decimal|real/): "Double",
        (~/(?i)bool|boolean/)             : "Boolean",
        (~/(?i)datetime|timestamp/)       : "java.util.Date",
        (~/(?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 && it.getKind() == ObjectKind.TABLE }.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, table, className, fields) }
}

def generate(out, table, className, fields) {
    def tableName = table.getName()
    out.println "package $packageName"
    out.println ""
    out.println "import lombok.Data;"
    out.println ""
    out.println "import javax.persistence.*;"
    out.println "import java.io.Serializable;"
    out.println ""
    out.println "@Data"
    out.println "@Entity"
    out.println "@Table(name = \"$tableName\")"
    out.println "public class $className  implements Serializable {"
    out.println ""
    // 判断自增
    if ((tableName + "_id").equalsIgnoreCase(fields[0].colum) || "id".equalsIgnoreCase(fields[0].colum)) {
        out.println "\t@Id"
        out.println "\t@GeneratedValue(strategy=GenerationType.IDENTITY)"
    }
    fields.each() {
        if (it.annos != "") out.println "  ${it.annos}"
        if (it.colum != it.name) {
            out.println "\t@Column(name = \"${it.colum}\")"
        }
        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),
                           colum: col.getName(),
                           type : typeStr,
                           annos: ""]]
    }
}

def javaName(str, capitalize) {
    def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }
            .join("").replaceAll(/[^\p{javaJavaIdentifierPart}]/, "_").replaceAll(/_/, "")
    capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
  1. 在database视图区域选择你想要生成的表,然后Scripted Extensions -> Generate POJOs.groovy
    可以使用ShiftCtrl多选

    image.png

  2. 弹出的文件选择框中,选择生成位置


    image.png
  3. 生成代码

package com.demo.jpa.entity;

import lombok.Data;

import javax.persistence.*;
import java.io.Serializable;

@Data
@Entity
@Table(name = "pv")
public class Pv  implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    private String ip;

    @Column(name = "channel_type")
    private Long channelType;

    private String openid;

    @Column(name = "create_time")
    private java.util.Date createTime;

}
生成成功提示

Spring Boot JPA实体类idea自动生成 其二

分享到: