欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

datagrip集成LOMBOK生成实体类

程序员文章站 2022-07-10 19:25:06
第一步:找到这个文件夹第二步:点击右键创建新文件,文件名随意,但是文件名后缀必须是".groovy";添加如下文件内容:import com.intellij.database.model.DasTableimport com.intellij.database.model.ObjectKindimport com.intellij.database.util.Caseimport com.intellij.database.util.DasUtilimport java.io.*impo...

第一步:找到这个文件夹
datagrip集成LOMBOK生成实体类
第二步:点击右键创建新文件,文件名随意,但是文件名后缀必须是".groovy";
添加如下文件内容:(适合jpa)

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.io.*
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|boolean|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 lombok.AllArgsConstructor;"
    out.println "import lombok.Data;"
    out.println "import lombok.NoArgsConstructor;"
    out.println "import javax.persistence.Column;"
    out.println "import javax.persistence.Entity;"
    out.println "import javax.persistence.Id;"
    out.println "import javax.persistence.Table;"
    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" +
            " * @author  dell\n" +
            " * @date "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
            " */"
    out.println ""
    out.println "@Data"
    out.println "@NoArgsConstructor"
    out.println "@AllArgsConstructor"
    out.println "@Entity"
    out.println "@Table (name =\""+table.getName() +"\")"
    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 != "") out.println "   ${it.annos}"

        if ((className + "_id").equalsIgnoreCase(it.colName) || "id".equalsIgnoreCase(it.colName)) {
            out.println "\t@Id"
        }

        if ("Date".equalsIgnoreCase(it.type)) {
            out.println '''\t@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")'''
            out.println '''\t@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")'''
        }

        // 输出成员变量
        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}"
//    }
    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()+"\" )"]
        fields += [comm]
    }
}

// 处理类名(这里是因为我的表都是以tab_命名的,所以需要处理去掉生成类名时的开头的tab_ 其它的类似具体详情可看代码,
// 如果你不需要那么请查找用到了 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}[_]]/, "_")
    // 去除开头的tab,如果是以t开头可以把
    //3..s.size() - 1 中的 3.. 改为 1..
    //并且把后面的 capitalize || s.length() == 3 改为 capitalize || s.length() == 1
    //其它的以此类推
    s = s[3..s.size() - 1]
    capitalize || s.length() == 3? 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;"
}

第三步:选中要生成实体类的数据库表(可以按住CTRL+鼠标左键连续选中好多个表一次性生成,也可以按数据库生成。)
datagrip集成LOMBOK生成实体类
第四步:生成的POJO+Lombok实体类如下所示:


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

/**
 * @author  dell
 * @date 2020-12-07 
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table (name ="user")
public class User  implements Serializable {

	private static final long serialVersionUID =  524258970393766098L;

	/**
	 * 自增id
	 */
   	@Column(name = "user_id" )
	@Id
	private Long userId;

	/**
	 * 登录名
	 */
   	@Column(name = "username" )
	private String username;

	/**
	 * qq官方唯一编号信息
	 */
   	@Column(name = "qq_open_id" )
	private String qqOpenId;

	/**
	 * 登录密码
	 */
   	@Column(name = "password" )
	private String password;

	/**
	 * 邮箱
	 */
   	@Column(name = "user_email" )
	private String userEmail;

	/**
	 * 新用户注册邮件激活唯一校验码
	 */
   	@Column(name = "user_email_code" )
	private String userEmailCode;

	/**
	 * 新用户是否已经通过邮箱激活帐号
	 */
   	@Column(name = "is_active" )
	private String isActive;

	/**
	 * 性别
	 */
   	@Column(name = "user_sex" )
	private String userSex;

	/**
	 * qq
	 */
   	@Column(name = "user_qq" )
	private String userQq;

	/**
	 * 手机
	 */
   	@Column(name = "user_tel" )
	private String userTel;

	/**
	 * 学历
	 */
   	@Column(name = "user_xueli" )
	private String userXueli;

	/**
	 * 爱好
	 */
   	@Column(name = "user_hobby" )
	private String userHobby;

	/**
	 * 简介
	 */
   	@Column(name = "user_introduce" )
	private String userIntroduce;

	/**
	 * 创建时间
	 */
   	@Column(name = "create_time" )
	private Long createTime;

	/**
	 * 修改时间
	 */
   	@Column(name = "update_time" )
	private Long updateTime;

}

OK,到此结束


bug1:提示,生成的实体类,存在外键的实体需要自己添加@id注解,因为重复判断和去除引起的(也就是说存在外键的实体生成的POJO没有@ID主键标识,作者到现在也没有解决,如果有人解决了,请发出来共享,谢谢。)。


再补:适合mybatis的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
import java.io.*
import java.text.SimpleDateFormat

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */
typeMapping = [
        (~/(?i)tinyint|smallint|mediumint/)      : "Integer",
        (~/(?i)int/)                             : "Long",
        (~/(?i)bool|boolean|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)
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "UTF-8"))
    printWriter.withPrintWriter {out -> generate(out, className, fields,table)}
}

def generate(out, className, fields,table) {
    out.println ""
    out.println "import lombok.AllArgsConstructor;"
    out.println "import lombok.Data;"
    out.println "import lombok.NoArgsConstructor;"
    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" +
            " * @author  dell\n" +
            " * @date "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
            " */"
    out.println ""
    out.println "@Data"
    out.println "@NoArgsConstructor"
    out.println "@AllArgsConstructor"
    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 ("Date".equalsIgnoreCase(it.type)) {
            out.println '''\t@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")'''
            out.println '''\t@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")'''
        }

        // 输出成员变量
        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 comm =[
                colName : col.getName(),
                name :  javaName(col.getName(), false),
                type : typeStr,
                commoent: col.getComment()]
        fields += [comm]
    }
}

// 处理类名(这里是因为我的表都是以tab_命名的,所以需要处理去掉生成类名时的开头的tab_ 其它的类似具体详情可看代码,
// 如果你不需要那么请查找用到了 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}[_]]/, "_")
    // 去除开头的tab,如果是以t开头可以把
    //3..s.size() - 1 中的 3.. 改为 1..
    //并且把后面的 capitalize || s.length() == 3 改为 capitalize || s.length() == 1
    //其它的以此类推
    s = s[3..s.size() - 1]
    capitalize || s.length() == 3? 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;"
}


再补:
tip1:如果是spring boot+mybatis开发,请在spring boot的配置文件中开启驼峰命名规则,如下配置:

mybatis:
  configuration:
#    开启mybatis的驼峰命名支持
    map-underscore-to-camel-case: true

tip2:如果是单独的mybatis开发,添加如下配置到配置文件中:

<configuration>
    <!--开启驼峰命名规则自动转换-->
    <settings>
    <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>

本文地址:https://blog.csdn.net/qq_44503987/article/details/110843522

相关标签: Lombok