首页 > 其他分享 >使用IDEA+groovy快速生成entity、dto、dao、service、serviceImpl

使用IDEA+groovy快速生成entity、dto、dao、service、serviceImpl

时间:2024-03-13 11:35:56浏览次数:26  
标签:groovy dto name service replaceAll println import def out

groovy代码

import com.intellij.database.model.DasTable
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 = ""
dtoPackageName = ""
daoPackageName = ""
servicePackageName = ""
serviceImplPackageName = ""
entityImport = ""
daoImport = ""
serviceImport = ""
baseEntityDir = ""
typeMapping = [
        (~/(?i)int|number/)               : "Long",
        (~/(?i)float|double|decimal|real/): "double",
        (~/(?i)datetime|timestamp/)       : "Timestamp",
        (~/(?i)date/)                     : "Date",
        (~/(?i)time/)                     : "Time",
        (~/(?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) {
    /*entity*/
    def tableName = table.getName()
    def className = javaName(tableName, true) + "Entity"
    def fields = calcFields(table)
    def entityDir = dir.toString() + "\\model\\entity"
    def entityBaseDir =  "net\\core\\base"
    packageName = entityDir.replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
    baseEntityDir = entityBaseDir.replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "")+".BaseEntity;"
    new File(entityDir, className + ".java").withPrintWriter("utf-8") { out -> generate(out, className, fields, tableName, table.getComment()) }
    entityImport = entityDir.replaceAll("\\\\", ".")
            .replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + "." + className + ";"

    /*DTO*/
    def dtoDir = dir.toString() + "\\model\\dto"
    def dtoClassName = javaName(tableName, true) + "DTO"
    dtoPackageName = dtoDir.replaceAll("\\\\", ".")
            .replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
    new File(dtoDir, dtoClassName + ".java").withPrintWriter("utf-8") { out -> generateDTO(out, className, dtoClassName, table.getComment()) }

    /*DAO*/
    def daoDir = dir.toString() + "\\dao"
    def daoClassName = javaName(tableName, true) + "Dao"
    daoPackageName = daoDir.replaceAll("\\\\", ".")
            .replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
    new File(daoDir, daoClassName + ".java").withPrintWriter("utf-8") { out -> generateDAO(out, className, daoClassName, table.getComment()) }
    daoImport = daoDir.replaceAll("\\\\", ".")
            .replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + "." + daoClassName + ";"

    /*Service*/
    def serviceDir = dir.toString() + "\\service"
    def serviceClassName = javaName(tableName, true) + "Service"
    servicePackageName = serviceDir.replaceAll("\\\\", ".")
            .replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
    new File(serviceDir, serviceClassName + ".java").withPrintWriter("utf-8") { out -> generateService(out, className, serviceClassName, table.getComment()) }
    serviceImport = serviceDir.replaceAll("\\\\", ".")
            .replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + "." + serviceClassName + ";"

    /*ServiceImpl*/
    def serviceImplDir = dir.toString() + "\\service\\impl"
    def serviceImplClassName = javaName(tableName, true) + "ServiceImpl"
    serviceImplPackageName = serviceImplDir.replaceAll("\\\\", ".")
            .replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
    new File(serviceImplDir, serviceImplClassName + ".java").withPrintWriter("utf-8") { out -> generateServiceImpl(out, className, serviceImplClassName, serviceClassName, daoClassName, table.getComment()) }


}


def generateDAO(out, entityClassName, daoClassName, tableComment){
    out.println "package $daoPackageName"
    out.println ""
    out.println "import io.swagger.annotations.ApiModelProperty;"
    out.println ""
    out.println "import $entityImport"
    out.println "import com.baomidou.mybatisplus.core.mapper.BaseMapper;"
    out.println "import org.apache.ibatis.annotations.Mapper;"
    out.println ""
    out.println "/**\n" +
            " * <P><B>Description</B>$tableComment Dao</P>\n" +
            " * RevisionTrail:(Date/Author/Description)\n" +
            " * " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new java.util.Date()) + " CREATE\n" +
            " *\n" +
            " * @author Ryan Huang\n" +
            " * @version 1.0\n" +
            " */"
    out.println "@Mapper"
    out.println "public interface $daoClassName extends BaseMapper<$entityClassName> {"
    out.println "}"
}

def generateService(out, entityClassName, serviceClassName, tableComment){
    out.println "package $servicePackageName"
    out.println ""
    out.println "import $entityImport"
    out.println "import com.baomidou.mybatisplus.extension.service.IService;"
    out.println ""
    out.println "/**\n" +
            " * <P><B>Description</B>$tableComment Service</P>\n" +
            " * RevisionTrail:(Date/Author/Description)\n" +
            " * " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new java.util.Date()) + " CREATE\n" +
            " *\n" +
            " * @author Ryan Huang\n" +
            " * @version 1.0\n" +
            " */"
    out.println "public interface $serviceClassName extends IService<$entityClassName> {"
    out.println "}"
}

def generateServiceImpl(out, entityClassName, serviceImplClassName, serviceClassName,  daoClassName, tableComment){
    out.println "package $serviceImplPackageName"
    out.println "import $entityImport"
    out.println "import org.springframework.stereotype.Service;"
    out.println "import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;"
    out.println "import $daoImport"
    out.println "import $serviceImport"
    out.println ""
    out.println "/**\n" +
            " * <P><B>Description</B>$tableComment ServiceImpl</P>\n" +
            " * RevisionTrail:(Date/Author/Description)\n" +
            " * " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new java.util.Date()) + " CREATE\n" +
            " *\n" +
            " * @author Ryan Huang\n" +
            " * @version 1.0\n" +
            " */"
    out.println "@Service"
    out.println "public class $serviceImplClassName extends ServiceImpl<$daoClassName, $entityClassName> implements $serviceClassName {"
    out.println "}"
}

def generateDTO(out, entityClassName, dtoClassName, tableComment) {
    out.println "package $dtoPackageName"
    out.println ""
    out.println "import com.baomidou.mybatisplus.annotation.TableName;"
    out.println "import io.swagger.annotations.ApiModel;"
    out.println ""
    out.println "import $entityImport"
    out.println ""
    out.println "/**\n" +
            " * <P><B>Description</B>$tableComment DTO</P>\n" +
            " * RevisionTrail:(Date/Author/Description)\n" +
            " * " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new java.util.Date()) + " CREATE\n" +
            " *\n" +
            " * @author Ryan Huang\n" +
            " * @version 1.0\n" +
            " */"
    out.println "@ApiModel(value = \"$tableComment" + "DTO\")"
    out.println "public class $dtoClassName extends $entityClassName {"
    out.println "}"
}

def generate(out, className, fields, tableName, tableComment) {
    out.println "package $packageName"
    out.println ""
    out.println "import com.baomidou.mybatisplus.annotation.TableName;"
    out.println "import com.baomidou.mybatisplus.annotation.TableField;"
    out.println "import io.swagger.annotations.ApiModelProperty;"
    out.println "import lombok.Getter;"
    out.println "import lombok.Setter;"
    out.println "import $baseEntityDir"
    out.println ""
    out.println "import java.sql.Timestamp;"
    out.println "import java.util.Date;"
    out.println "import java.sql.Time;"
    out.println ""
    out.println "/**\n" +
            " * <P><B>Description</B>$tableComment</P>\n" +
            " * RevisionTrail:(Date/Author/Description)\n" +
            " * " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new java.util.Date()) + " CREATE\n" +
            " *\n" +
            " * @author Ryan Huang\n" +
            " * @version 1.0\n" +
            " */"
    out.println "@Getter"
    out.println "@Setter"
    out.println "@TableName(\"$tableName\")"
    out.println "public class ${className} extends BaseEntity {"
    fields.each() {
        if ("id".compareToIgnoreCase(it.name) != 0
                && "Creator".compareToIgnoreCase(it.name) != 0
                && "Crtname".compareToIgnoreCase(it.name) != 0
                && "Create".compareToIgnoreCase(it.name) != 0
                && "Modifiedby".compareToIgnoreCase(it.name) != 0
                && "Mfyname".compareToIgnoreCase(it.name) != 0
                && "Modified".compareToIgnoreCase(it.name) != 0
                && "Status".compareToIgnoreCase(it.name) != 0) {
            if (it.annos != "") out.println "  ${it.annos}"
            out.println ""
            out.println "    /**"
            out.println "     * ${it.commoent.toString()}"
            out.println "     */"
            if (isNotEmpty(it.commoent)) {
                out.println "    @ApiModelProperty(value = \"" + it.commoent.toString() + "\")"
            }
            out.println "    @TableField(value=\"${it.tableCol}\")"
            out.println "    private ${it.type} ${it.name};"
        }
    }
    out.println ""
    fields.each() {
        //过滤字段
        if ("id".compareToIgnoreCase(it.name) != 0
                && "Creator".compareToIgnoreCase(it.name) != 0
                && "Crtname".compareToIgnoreCase(it.name) != 0
                && "Create".compareToIgnoreCase(it.name) != 0
                && "Modifiedby".compareToIgnoreCase(it.name) != 0
                && "Mfyname".compareToIgnoreCase(it.name) != 0
                && "Modified".compareToIgnoreCase(it.name) != 0
                && "Status".compareToIgnoreCase(it.name) != 0) {
            //get set方法
//            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),
                           tableCol: col.getName(),
                           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
}

IDEA使用

1、将groovy文件添加到IDEA

2、选择需要生成的表,右键Tools->Scripted Extendsions->generate POJOs.groovy

标签:groovy,dto,name,service,replaceAll,println,import,def,out
From: https://www.cnblogs.com/IamHzc/p/18070255

相关文章

  • jmeter5.1进行webservice接口测试
    原始代码展示如下:分别为soap1.1和soap1.2的源代码:测试测试窗体只能用于来自本地计算机的请求。SOAP1.1以下是SOAP1.2请求和响应示例。所显示的占位符需替换为实际值。POST/WuService.asmxHTTP/1.1Host:192.168.20.230Content-Type:text/xml;charset=utf-8Cont......
  • Kubernetes Service
    标签及标签选择器是什么,如何使用标签是键值对类型,标签可以附加到任何资源对象上,主要用于管理对象,查询和筛选。标签常被用于标签选择器的匹配度检查,从而完成资源筛选;一个资源可以定义一个或多个标签在其上面。标签选择器,标签要与标签选择器结合在一起,标签选择器允许我们选择标记......
  • k8s中port-forward 与service的nodeport区别
    在Kubernetes中,port-forward和Service的NodePort是两种将外部流量引入集群内部Pod的方法,但它们在实现方式、使用场景和安全性等方面有所不同。port-forward:实现方式:kubectlport-forward命令允许你将本地机器上的一个端口转发到Kubernetes集群中的一个Pod上的端口。这是一种......
  • 实体类与数据库的直接交互问题,DTO,AutoMapper的使用
    实体类、DTO与数据库交互的最佳实践实体类与数据库的直接交互问题在软件开发中,实体类通常被设计为反映业务域的数据模型。这些实体类可能包含以下元素:特性(Attributes):用于定义实体属性的额外信息,比如数据验证规则或ORM(对象关系映射)框架的映射信息。继承关系:实体之间可能存......
  • 一招解决向日葵红叉错误can't connect service 自启动完美运行
    原文链接:https://baijiahao.baidu.com/s?id=1764923932060464102&wfr=spider&for=pc解决过程:1、首先从启动项入手,使用360启动项管理查看,没有任何问题。2、重新安装向日葵,重启电脑,依旧红叉can'tconnectservice报错,无效。3、尝试使用autoruns软件进行查看,也未发现任何......
  • 收藏:关于RADIUS的简明解释(Remote Authentication Dial In User Service远程用户拨号认
    收藏:关于RADIUS的简明解释(RemoteAuthenticationDialInUserService远程用户拨号认证系统)来自:https://baike.sogou.com/v4710162.htm?ch=frombaikevr&fromTitle=RADIUSRADIUS:RemoteAuthenticationDialInUserService,远程用户拨号认证系统(与radius半径的单词拼法一致)......
  • 【HMS Core】ToolKit,Merchant Service has not been enabled yet
    ​【问题描述】集成应用内支付时,一直提示未开通商户服务,实际商户服务已开通。​【解决方案】一般是由于AndroidStudio里的开发者账户和联盟网站对应开通商户服务的不是同一个账户造成的​PS:如果有团队帐号,还需注意,是否是团队帐号开通的,需选择正确的team。​......
  • ssts-hospital-web-master项目实战记录三十:项目迁移-Hook实现(useSystemService)
    记录时间:2024-02-29一、useSystemService模块实现service/system-service/useTerminalService.tsimporthydatefrom'@/utils/date-format'import{LogInfo}from'@/framework/utils/log-local'import{Device}from'@/types/device'impor......
  • servlet.service() for servlet [dispatcherservlet] in context with path []
    Sevlet.service()forservlet[dispatcherServlef]incontextwithpath[|threwexception[Requestprocessingfailed;nestedexceptioniorg.springframework.web.client.ResourceAccessException:/0erroronGETrequestfor"htt.:llocalhost8081.user1":......
  • Oracle-JPA扩展工具-原生SQL查询并返回自定义DTO
    Java-JPA原生SQL查询返回自定义DTO:importcom.tjgeo.njsosms.framework.repository.IBaseRepository;importcom.tjgeo.njsosms.risk.support.entity.Source;importorg.springframework.data.jpa.repository.Query;importjava.util.List;/***${Description}**@......