idea database 快速生成实体类 注释 序列化

本文介绍了一种使用Groovy脚本自动生成Java POJO类的方法,通过解析数据库表结构,映射到Java实体类,简化了代码生成过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

按着下面步骤:

 

 

 

这个 Generate MyPOJOs.groovy 是我自定义的

在这里创建才可以用

这里创建一个文件即可。把下面代码复制进去即可

import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import java.io.*
/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "com.xxx.busi.entity;;"
typeMapping = [
        (~/(?i)int/)                      : "Long",
        (~/(?i)float|double|decimal|real/): "Double",
        (~/(?i)datetime|timestamp/)       : "java.util.Date",
        (~/(?i)date/)                     : "java.util.Date",
        (~/(?i)time/)                     : "java.util.Date",
        (~/(?i)/)                         : "String"
]

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 tableNameDispose = table.getName().substring((table.getName().indexOf("dr_") + 2), table.getName().length())
    out.println tableNameDispose
    def className = javaName(tableNameDispose, true)
    out.println className
    def fields = calcFields(table)
    PrintWriter output = new PrintWriter(new OutputStreamWriter(new FileOutputStream( new File(dir, className + ".java")), "utf-8"))
    output.withPrintWriter { out -> generate(out, className, fields,table.getName()) }
}

def generate(out, className, fields,tableName) {
    out.println "package $packageName"
    out.println "import java.io.Serializable;"
    out.println "import javax.persistence.Entity;"
    out.println "import javax.persistence.Table;"
    out.println ""
    out.println "@Entity"
    out.println "@Table(name = \"${tableName}\")"
    out.println "public class $className implements Serializable{"
    out.println ""
    def msum= (long)(Math.random()*1000000000000000000+1000000000000000000)
    out.println  "  private static final long serialVersionUID = ${msum}L;"
    fields.each() {
        if (isNotEmpty(it.commoent)) {
            out.println ""

            out.println "\t/**"
            out.println "\t * ${it.commoent}"
            out.println "\t */"
        }
        if (it.annos != "") out.println "  ${it.annos}"
        out.println "  private ${it.type} ${it.name};"
    }
    out.println ""
    fields.each() {
        out.println ""
        out.println "  public ${it.type} get${it.name.capitalize()}() {"
        out.println "    return ${it.name};"
        out.println "  }"
        out.println ""
        out.println "  public void set${it.name.capitalize()}(${it.type} ${it.name}) {"
        out.println "    this.${it.name} = ${it.name};"
        out.println "  }"
        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),
                           type : typeStr,
                           commoent: col.getComment(),
                           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
}


 

当然这些代码一般都会大概看的懂,可以改成只能想要的那种格式

 

MyBatisCodeHelper-Pro插件免费版 Features Type safe sql support, plugin can recognize mybatis dynamic sql Code Formatter Generate mybatis crud code by Intellij database table or add a database connection Generate mybatis sql based on mybatis interface method name like spring data jpa, with this, you don't have to write most sql for non join query support generate statement with if test Database generate crud could generate multiple times when you add or delete columns, plugin will auto merge code Full mybatis sql auto complete, recognize mybatis tag in xml, like where trim set include ect,provide sql completion after those tag Jump from mybatis dao interface to mapper xml each other Refactor for mybatis interface method name,refid,resultMap ect Auto complete for mybatis param,if test,foreach,resultMap,refid in sql Generate create table sql from java class Mybatis Param refactor and inspection Ognl support, if test when test ${ bind foreach collection, refactor and inspection and auto completion Jump from refid resultMap to their definition, refactor their name as well Generate page query by mapper interface method Spring support for mybatis, inject mybatis mapper to spring bean,support SpringBoot Refid,resultMap,keyProperty,property auto complete Add @param for mapper method Resultmap column complete and inspection by parse reference select statement Auto map resultMap column and property Generate mybatis mapper testcase from mybatis interface method by database connection, make you test method quicker Full inspection for mybatis, like unused sql in xml, mapper method not have sql in xml, check if resultMap property is right ect https://github.com/gejun123456/MyBatisCodeHelper-Pro to learn more. How to use view on https://github.com/gejun123456/MyBatisCodeHelper-Pro qqGroup:914051156
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值