idea groovy自定义自动生成实体 dao/mapper service等,支持表注释 字段注释

2 篇文章 0 订阅

均带实体类注释和字段注释
(每个人的代码风格习惯 稍有不同,自行更改即可)
dao/mapper service controller基本上一样 些许改动

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

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */
packageName = ""
comment = ""
typeMapping = [
        (~/(?i)tinyint|smallint|mediumint/)      : "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) }
}

def generate(table, dir) {
    def className = javaName(table.getName(), true)
    def fields = calcFields(table)
    packageName = getPackageName(dir)
    comment=table.getComment();
    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 java.io.Serializable;"
    out.println "import com.test.mybatisplus.annotation.IdType;"
    out.println "import com.test.mybatisplus.annotation.TableId;"
    out.println "import com.fasterxml.jackson.databind.annotation.JsonSerialize;"
    out.println "import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;"
    out.println "import com.test.common.core.web.domain.BaseEntity;"
    out.println "import lombok.AllArgsConstructor;"
    out.println "import lombok.Data;"
    out.println "import lombok.NoArgsConstructor;"
    out.println "import lombok.experimental.Accessors;"


    Set types = new HashSet()
    def commonNames = ['createBy', 'createTime', 'updateBy', 'updateTime', 'delFlag','remark']
    fields.each() {
        if (it.name in commonNames) {
        } else {
            types.add(it.type)
        }
    }

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

    if (types.contains("InputStream")) {
        out.println "import java.io.InputStream;"
    }
    out.println ""
    out.println "/**\n" +
            " * @Description  $comment \n" +
            " * @Author lily \n" +
            " * @Date "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
            " */"
    out.println ""


    out.println "@Data"
    out.println "@NoArgsConstructor"
    out.println "@AllArgsConstructor"
    out.println "@Accessors(chain = true)"
    out.println "public class $className extends BaseEntity {"
    out.println ""
    out.println genSerialID()
    fields.each() {
//        if (! ${it.name} in commonNames){
        if (it.name in commonNames) {
        }else{
            out.println ""
        // 输出注释
        if (isNotEmpty(it.commoent)) {
            out.println "\t/**"
            out.println "\t * ${it.commoent.toString()}"
            out.println "\t */"
        }
        if (it.isId) out.println "    @TableId(type = IdType.ASSIGN_ID)"
        if (it.isId) out.println "    @JsonSerialize(using= ToStringSerializer.class)"
//        if (it.annos != "") out.println "   ${it.annos.replace("[@Id]", "")}"
        if (it.type == "Date") out.println "    @JsonFormat(pattern=\"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\") \n" +
                "    @DateTimeFormat(pattern = \"yyyy-MM-dd\") "
        if (it.annos != "") out.println "   ${it.annos}"

        // 输出成员变量
        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) {
    def primaryKey = DasUtil.getPrimaryKey(table)
    DasUtil.getColumns(table).reduce([]) { fields, col ->
        def spec = Case.LOWER.apply(col.getDataType().getSpecification())
        def colName = col.getName()
        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 = \""+colName+"\" )"*/,
                isId : primaryKey != null && DasUtil.containsName(colName, primaryKey.getColumnsRef()),
        ]

//        if("id".equals(Case.LOWER.apply(col.getName())))
//            comm.annos +=["@Id"]
        fields += [comm]
    }
}

// 处理类名(这里是因为我的表都是以t_命名的,所以需要处理去掉生成类名时的开头的T,
// 如果你不需要那么请查找用到了 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}[_]]/, "_")
    // 去除开头的T  http://developer.51cto.com/art/200906/129168.htm
    s = s[1..s.size() - 1]
    capitalize || s.length() == 1? 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;"
    return "\tprivate static final long serialVersionUID =  1L;"
}



entity生成效果如下:

package com.test.informatization.domain;

import com.test.mybatisplus.annotation.IdType;
import com.test.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.test.common.core.web.domain.BaseEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

/**
 * @Description  业务单号生成规则表 
 * @Author  
 * @Date 2022-06-09 
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class Test extends BaseEntity {

	private static final long serialVersionUID =  1L;

    @TableId(type = IdType.ASSIGN_ID)
    @JsonSerialize(using= ToStringSerializer.class)
	private String id;

	private String test;

}

dao/mapper 生成代码脚本如下:

package src

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 = "" // 需手动配置 生成的 dao 所在包位置
comment=""
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 baseName = javaName(table.getName(), true)
    comment =table.getComment();
    packageName = getPackageName(dir)
    new File(dir, baseName + "Mapper.java").withPrintWriter { out -> generateInterface(out, baseName) }
}

// 获取包所在文件夹路径
def getPackageName(dir) {
    return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}


def generateInterface(out, baseName) {
    out.println "package $packageName"
//    out.println "import cn.xx.entity.${baseName}Entity;" // 需手动配置
    out.println "import com.test.domain.${baseName};" // 需手动配置
    out.println "import com.test.mybatisplus.core.mapper.BaseMapper;" // 需手动配置


    out.println ""
    out.println "/**\n" +
            " * @Description $comment \n" +
            " * @Author lily \n" +
            " * @Date "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
            " */"
    out.println ""


//    out.println "@Repository"
    out.println "public interface ${baseName}Mapper extends BaseMapper<${baseName}> {" // 可自定义
    out.println ""
    out.println "}"
}

def javaName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    name = capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

dao/mapper 生成代码如下:

package com.test.mapper;
import com.test.Test;
import com.test.mybatisplus.core.mapper.BaseMapper;

/**
 * @Description 业务单号生成规则表 
 * @Author lily 
 * @Date 2022-06-09 
 */

public interface TestMapper extends BaseMapper<Test> {

}

service 生成代码脚本如下:

package src

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 = "" // 需手动配置 生成的 dao 所在包位置
comment=""
baseNameLowerBegin=""
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 baseName = javaName(table.getName(), true)
    baseNameLowerBegin= baseName.uncapitalize()
    comment =table.getComment();
    packageName = getPackageName(dir)
    new File(dir, baseName + "Service.java").withPrintWriter { out -> generateInterface(out, baseName) }
}

// 获取包所在文件夹路径
def getPackageName(dir) {
    return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}


def generateInterface(out, baseName) {
    out.println "package $packageName"
//    out.println "import cn.xx.entity.${baseName}Entity;" // 需手动配置
    out.println "import com.test.informatization.mapper.${baseName}Mapper;" // 需手动配置
    out.println "import org.springframework.stereotype.Service;" // 需手动配置
    out.println "import org.springframework.beans.factory.annotation.Autowired;"


    out.println ""
    out.println "/**\n" +
            " * @Description $comment \n" +
            " * @Author lily \n" +
            " * @Date "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
            " */"
    out.println ""


    out.println "@Service"
    out.println "public interface ${baseName}Service {" // 可自定义

    out.println ""
    out.println "  @Autowired"
    out.println "  private ${baseName}Mapper ${baseNameLowerBegin}Mapper;"



    out.println "}"
}

def javaName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    name = capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

service 效果如下:

package com.test.service;
import com.test.mapper.TestMapper;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description 测试表 
 * @Author lily 
 * @Date 2022-06-09 
 */

@Service
public interface TestService {

  @Autowired
  private TestMapper testMapper;
}

controller 生成代码脚本 如下:

package src

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 = "" // 需手动配置 生成的 dao 所在包位置
comment=""
baseNameLowerBegin=""
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 baseName = javaName(table.getName(), true)
    baseNameLowerBegin= baseName.uncapitalize()
    comment =table.getComment();
    packageName = getPackageName(dir)
    new File(dir, baseName + "Controller.java").withPrintWriter { out -> generateInterface(out, baseName) }
}

// 获取包所在文件夹路径
def getPackageName(dir) {
    return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}


def generateInterface(out, baseName) {
    out.println "package $packageName"
//    out.println "import cn.xx.entity.${baseName}Entity;" // 需手动配置
    out.println "import com.test.informatization.service.${baseName}Service;" // 需手动配置
    out.println "import org.springframework.web.bind.annotation.*;" // 需手动配置
    out.println "import org.springframework.beans.factory.annotation.Autowired;"
    out.println "import io.swagger.annotations.Api;"
//    out.println "import org.springframework.stereotype.Repository;"     //GMS不需要  service才需要这个注释

    out.println ""
    out.println "/**\n" +
            " * @Description $comment \n" +
            " * @Author lily \n" +
            " * @Date "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
            " */"
    out.println ""


    out.println "@RestController"
    out.println "@Api(\"/$comment\")"
    out.println "@RequestMapping(\"/$baseNameLowerBegin\")"

    out.println "public class ${baseName}Controller {" // 可自定义

    out.println ""
    out.println "  @Autowired"
    out.println "  private ${baseName}Service ${baseNameLowerBegin}Service;"



    out.println "}"
}

def javaName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    name = capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

controller 生成效果如下:

package com.test.controller;
import com.test.service.TestService;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.Api;

/**
 * @Description 业务单号生成规则表 
 * @Author lily 
 * @Date 2022-06-09 
 */

@RestController
@Api("/业务单号生成规则表")
@RequestMapping("/test")
public class TestController {

  @Autowired
  private TestService testService;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值