IDEA根据数据表自动生成Entity JPADao DTO groovy 脚本

先上效果:


在哪儿用?
上图:

目录

Entity:

DTO:

DAO:


Entity:

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

/*
 * @勒是啥子  IDEA database 生成 java实体工具脚本
 * @哪儿来的 插件本生有代码,不一样的都是网上抄的略有改动。不知出处网上到处都是。
 * @囊个用 IDEA database 插件 新建mysql连接 ,在表的列表中种选你要生成的表,然后
 * -> Scripted Extensions  -> Generate POJOs.groovy
 * 这个脚本都是 Generate POJOs.groovy 里面的代码。
 */


packageName = ""
typeMapping = [
        (~/(?i)tinyint|smallint|mediumint|int/)  : "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) }
}

/**
 * 生成代码
 * @param table
 * @param dir
 * @return
 */
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) }
}

/**
 * 获取包所在文件夹路径
 * @param dir
 * @return
 */
def getPackageName(dir) {
    return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}
/**
 * 生成代码 模版
 * @param table
 * @param dir
 * @return
 */
def generate(out, className, fields, table) {
    out.println "package $packageName"
    out.println ""
    out.println "import javax.persistence.*;"
   /* out.println "import javax.persistence.Entity;"
    out.println "import javax.persistence.Table;"*/
    out.println "import java.io.Serializable;"
    out.println "import lombok.Data;"

    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;"
    }
    String classtitleName = table.getName();
    if (null != table.getComment() && "" != table.getComment()) {
        classtitleName = table.getComment() + "(" + table.getName() + ")";
    }


    //类注释
    out.println ""
    out.println "/**\n" +
            " * @Title " + classtitleName + "\n" +
            " * @Description  \n" +
            " * @author System Generation  \n" +
            " * @Date " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
            " */"
    //类注解
    out.println ""
    out.println "@Entity"
    out.println "@Table ( name =\"" + table.getName() + "\" )"
    out.println "@Data"
    //类
    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.replace("[@Id]", "")}"
            out.println "   ${it.annos}"
        }
        // 输出 成员变量
        out.println "\tprivate ${it.type} ${it.name};"
    }
    out.println ""
    out.println "}"
}
/**
 * 数据
 * @param table
 * @return
 */
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 annos = "\t@Column(name = \"" + col.getName() + "\" )";
        if (null != col.getComment() && "" != col.getComment()) {
            annos = "\t@Column(name = \"" + col.getName() + "\" , columnDefinition = \"" + col.getComment() + "\'\")";
        }
        // 这儿网上没找 咋个设置 @ID 你们要去看看源码 ideaIU-XXX.win\plugins\DatabaseTools\lib
        if ("id".equals(Case.LOWER.apply(col.getName()))) {
            annos = "\t@Id \r" + annos
        }

        def comm = [
                colName : col.getName(),
                name    : javaName(col.getName(), false),
                type    : typeStr,
                commoent: col.getComment(),
                annos   : annos]

        fields += [comm]
    }
}

/**
 * 生成类名
 *
 * 处理类名(这里是因为我的表都是以t_命名的,所以需要处理去掉生成类名时的开头的T,
 *  如果你不需要那么请查找用到了 javaClassName这个方法的地方修改为 javaName 即可)
 * @param str
 * @param capitalize
 * @return
 */
def javaClassName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    s = s[1..s.size() - 1]//去掉第一个
    capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
/**
 * 生成类名
 *
 * @param str
 * @param capitalize
 * @return
 */
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
}
/**
 *  生成序列化ID
 * @return
 */
static String genSerialID() {
    return "\tprivate static final long serialVersionUID =  " + Math.abs(new Random().nextLong()) + "L;"
}
/*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('')
    }
}*/

DTO:
 

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

/*
 * @勒是啥子  IDEA database 生成 java实体工具脚本
 * @哪儿来的 插件本生有代码,不一样的都是网上抄的略有改动。不知出处网上到处都是。
 * @囊个用 IDEA database 插件 新建mysql连接 ,在表的列表中种选你要生成的表,然后
 * -> Scripted Extensions  -> Generate POJOs.groovy
 * 这个脚本都是 Generate POJOs.groovy 里面的代码。
 */


packageName = ""
typeMapping = [
        (~/(?i)tinyint|smallint|mediumint|int/)  : "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) }
}

/**
 * 生成代码
 * @param table
 * @param dir
 * @return
 */
def generate(table, dir) {

    def className = javaName(table.getName(), true)
    def fields = calcFields(table)
    packageName = getPackageName(dir)

    String dirstrq = dir.toString() + "/dto/" + className + "DTO.java";
    File file = new File(dirstrq)
    if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs()
        file.createNewFile()
    }
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))
    printWriter.withPrintWriter { out -> generate(out, className, fields, table) }


    File sourceFile = new File("C:\\Users\\zjj\\.IntelliJIdea2018.3\\config\\extensions\\com.intellij.database\\schema\\GenerateJPADao.groovy");//加载脚本文件

//获取class
    Class groovyClass = new GroovyClassLoader(getClass().getClassLoader()).parseClass(sourceFile);
//示例化对象
    GroovyObject myObject = (GroovyObject) groovyClass.newInstance();
    myObject.generate(table, dir);
//    new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields,table) }
}

/**
 * 获取包所在文件夹路径
 * @param dir
 * @return
 */
def getPackageName(dir) {
    return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ""
}
/**
 * 生成代码 模版
 * @param table
 * @param dir
 * @return
 */
def generate(out, className, fields, table) {
    out.println "package $packageName" + ".dto;"
    out.println ""
    out.println "import $packageName" + ".$className;"
    out.println "import lombok.Data;"
    out.println "import io.swagger.annotations.ApiModelProperty;"

    Set types = new HashSet()

    fields.each() {
        types.add(it.type)
    }

    if (types.contains("Date")) {
        out.println "import java.util.Date;"
        out.println "import org.springframework.format.annotation.DateTimeFormat;"
    }

    if (types.contains("InputStream")) {
        out.println "import java.io.InputStream;"
    }
    String classtitleName = table.getName();
    if (null != table.getComment() && "" != table.getComment()) {
        classtitleName = table.getComment() + "(" + table.getName() + ")";
    }


    //类注释
    out.println ""
    out.println "/**\n" +
            " * @Description  " + classtitleName + "的DTO \n" +
            " * @author System Generation  \n" +
            " * @Date " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
            " */"
    //类注解
    out.println ""
    out.println "@Data"
    //类
    out.println "public class $className" + "DTO  extends $className {"
    out.println ""
    //序列化
    //out.println genSerialID()
    //成员变量
    fields.each() {
        out.println ""
        // 输出 注释
        if (isNotEmpty(it.commoent)) {
            out.println "\t@ApiModelProperty(value = \"${it.commoent.toString()}\")"
        }
        if (it.type?.toString().equals("Date")) {
            out.println "\t@DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")"
        }
        // 输出 成员变量
        out.println "\tprivate ${it.type} ${it.name};"
    }
    out.println ""
    out.println "}"
}
/**
 * 数据
 * @param table
 * @return
 */
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 annos = "\t@Column(name = \"" + col.getName() + "\" )";
        if (null != col.getComment() && "" != col.getComment()) {
            annos = "\t@Column(name = \"" + col.getName() + "\" , columnDefinition = \"" + col.getComment() + "\'\")";
        }
        // 这儿网上没找 咋个设置 @ID 你们要去看看源码 ideaIU-XXX.win\plugins\DatabaseTools\lib
        if ("id".equals(Case.LOWER.apply(col.getName()))) {
            annos = "\t@Id \r" + annos
        }

        def comm = [
                colName : col.getName(),
                name    : javaName(col.getName(), false),
                type    : typeStr,
                commoent: col.getComment(),
                annos   : annos]

        fields += [comm]
    }
}

/**
 * 生成类名
 *
 * 处理类名(这里是因为我的表都是以t_命名的,所以需要处理去掉生成类名时的开头的T,
 *  如果你不需要那么请查找用到了 javaClassName这个方法的地方修改为 javaName 即可)
 * @param str
 * @param capitalize
 * @return
 */
def javaClassName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    s = s[1..s.size() - 1]//去掉第一个
    capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
/**
 * 生成类名
 *
 * @param str
 * @param capitalize
 * @return
 */
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
}
/**
 *  生成序列化ID
 * @return
 */
static String genSerialID() {
    return "\tprivate static final long serialVersionUID =  " + Math.abs(new Random().nextLong()) + "L;"
}



DAO:

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

/*
 * @勒是啥子  IDEA database 生成 java实体工具脚本
 * @哪儿来的 插件本生有代码,不一样的都是网上抄的略有改动。不知出处网上到处都是。
 * @囊个用 IDEA database 插件 新建mysql连接 ,在表的列表中种选你要生成的表,然后
 * -> Scripted Extensions  -> Generate POJOs.groovy
 * 这个脚本都是 Generate POJOs.groovy 里面的代码。
 */


packageName = ""
typeMapping = [
        (~/(?i)tinyint|smallint|mediumint|int/)  : "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) }
}

/**
 * 生成代码
 * @param table
 * @param dir
 * @return
 */
def generate(table, dir) {

    def className = javaName(table.getName(), true)
    def fields = calcFields(table)
    packageName = getPackageName(dir)

    String dirstrq = dir.toString() + "/dao/" + className + "Dao.java";
    File file = new File(dirstrq)
    if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs()
        file.createNewFile()
    }
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))
    printWriter.withPrintWriter { out -> generate(out, className, fields, table) }

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

/**
 * 获取包所在文件夹路径
 * @param dir
 * @return
 */
def getPackageName(dir) {
    return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ""
}
/**
 * 生成代码 模版
 * @param table
 * @param dir
 * @return
 */
def generate(out, className, fields, table) {
    out.println "package $packageName" + ".dao;"
    out.println ""
    out.println "import $packageName" + ".$className;"
    out.println "import org.springframework.data.jpa.repository.JpaRepository;"
    out.println "import org.springframework.data.jpa.repository.JpaSpecificationExecutor;"
    out.println "import org.springframework.stereotype.Repository;"
    Set types = new HashSet()

    fields.each() {
        types.add(it.type)
    }


    String classtitleName = table.getName();
    if (null != table.getComment() && "" != table.getComment()) {
        classtitleName = table.getComment() + "(" + table.getName() + ")";
    }


    //类注释
    out.println ""
    out.println "/**\n" +
            " * @Description  " + classtitleName + "的Dao \n" +
            " * @author System Generation  \n" +
            " * @Date " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
            " */"
    //类注解
    out.println ""
    out.println "@Repository"
    //类
    out.println "public interface $className" + "Dao  extends JpaRepository<$className, String>, JpaSpecificationExecutor<$className>  {"
    out.println ""
    //成员变量
   /* fields.each() {
        out.println ""
        // 输出 注释
        if (isNotEmpty(it.commoent)) {
            out.println "\t@ApiModelProperty(value = \"${it.commoent.toString()}\")"
        }
        if (it.type?.toString().equals("Date")) {
            out.println "\t@DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")"
        }
        // 输出 成员变量
        out.println "\tprivate ${it.type} ${it.name};"
    }*/
    out.println ""
    out.println "}"
}
/**
 * 数据
 * @param table
 * @return
 */
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 annos = "\t@Column(name = \"" + col.getName() + "\" )";
        if (null != col.getComment() && "" != col.getComment()) {
            annos = "\t@Column(name = \"" + col.getName() + "\" , columnDefinition = \"" + col.getComment() + "\'\")";
        }
        // 这儿网上没找 咋个设置 @ID 你们要去看看源码 ideaIU-XXX.win\plugins\DatabaseTools\lib
        if ("id".equals(Case.LOWER.apply(col.getName()))) {
            annos = "\t@Id \r" + annos
        }

        def comm = [
                colName : col.getName(),
                name    : javaName(col.getName(), false),
                type    : typeStr,
                commoent: col.getComment(),
                annos   : annos]

        fields += [comm]
    }
}

/**
 * 生成类名
 *
 * 处理类名(这里是因为我的表都是以t_命名的,所以需要处理去掉生成类名时的开头的T,
 *  如果你不需要那么请查找用到了 javaClassName这个方法的地方修改为 javaName 即可)
 * @param str
 * @param capitalize
 * @return
 */
def javaClassName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    s = s[1..s.size() - 1]//去掉第一个
    capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
/**
 * 生成类名
 *
 * @param str
 * @param capitalize
 * @return
 */
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
}



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值