Idée de code de génération inverse (prenez la base de données MySQL comme exemple)

Ouvrez les paramètres de la base de données d'idées

Affichage -> Fenêtres d'outils -> Base de données, ouvrez la
Insérez la description de l'image ici
page de configuration de la base de données , il devrait y avoir une boîte rouge sur le côté droit de la page, ou vous pouvez l'ouvrir via la base de données sur le côté droit de la boîte rouge
Insérez la description de l'image ici

Base de données de configuration

+ Sign -> Data Source -> MySQL, entrez dans la page de configuration
Insérez la description de l'image ici

Remplissez les informations de configuration et vérifiez
Insérez la description de l'image ici

Une coche verte apparaît et la vérification est réussie
Insérez la description de l'image ici

Si ce qui suit apparaît en bas de la page, cliquez sur Télécharger pour télécharger le pilote
Insérez la description de l'image ici

Après avoir configuré et cliqué sur OK, les informations de la base de données apparaissent sur le côté droit de la page
Insérez la description de l'image ici

Créer un fichier groovy

Insérez la description de l'image ici

Ecrire un fichier 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.text.SimpleDateFormat

packageName = ""

// 表字段类型与Java的对应关系
typeMapping = [
        (~/(?i)tinyint|smallint|mediumint|int/)  : "Integer",
        (~/(?i)bool|bit/)                        : "Boolean",
        (~/(?i)float|double|decimal|real/)       : "BigDecimal",
        (~/(?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 = javaClassName(table.getName(), true)
    def fields = calcFields(table)
    packageName = getPackageName(dir)
    packageName = packageName.toString().replaceAll(";", "")

    def entityDir = dir.toString() + "\\entity"
    createDir(entityDir)
    PrintWriter entityPrintWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(entityDir, className + ".java")), "UTF-8"))
    entityPrintWriter.withPrintWriter {
    
     out -> entity(out, className, fields, table) }

    def mapperDir = dir.toString() + "\\dao"
    createDir(mapperDir)
    PrintWriter mapperPrintWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(mapperDir, className + "Mapper.java")), "UTF-8"))
    mapperPrintWriter.withPrintWriter {
    
     out -> mapper(out, className) }

    def serviceDir = dir.toString() + "\\service"
    createDir(serviceDir)
    PrintWriter servicePrintWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(serviceDir, className + "Service.java")), "UTF-8"))
    servicePrintWriter.withPrintWriter {
    
     out -> service(out, className) }

    def implDir = dir.toString() + "\\service\\impl"
    createDir(implDir)
    PrintWriter implPrintWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(implDir, className + "ServiceImpl.java")), "UTF-8"))
    implPrintWriter.withPrintWriter {
    
     out -> impl(out, className) }
}

/**
 * 创建目录
 * @param path 路径
 * @return
 */
static def createDir(path) {
    
    
    File dir = new File(path);
    if (!dir.exists()) {
    
    
        dir.mkdirs();
    }
}

/**
 * 获取package
 * @param dir 选择的目录
 * @return package
 */
static def getPackageName(dir) {
    
    
    return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}

/**
 * 实体类生成
 * @param out 实体类输出流
 * @param className 类名
 * @param fields 表字段信息
 * @param table 表
 * @return 实体类输出流
 */
def entity(out, className, fields, table) {
    
    
    out.println "package $packageName" + ".entity;"
    out.println ""
    out.println "import io.swagger.annotations.ApiModel;"
    out.println "import io.swagger.annotations.ApiModelProperty;"
    out.println "import lombok.Data;"
    out.println ""
    out.println "import javax.persistence.Column;"
    out.println "import javax.persistence.Entity;"
    out.println "import javax.persistence.Table;"
    out.println "import javax.persistence.GeneratedValue;"
    out.println "import javax.persistence.Id;"
    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;"
    }

    if (types.contains("BigDecimal")) {
    
    
        out.println "import java.math.BigDecimal;"
    }
    out.println ""
    out.println "/**\n" +
            " * @Description  \n" +
            " * @Author: hyy\n" +
            " * @Date " + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + " \n" +
            " */"
    out.println ""
    out.println "@Data"
    out.println "@Entity"
    out.println "@Table ( name =\"" + table.getName() + "\" )"
    out.println "@ApiModel(description = \"" + table.getName() + "\")"
    out.println "public class $className implements Serializable {"
    fields.each() {
    
    
        out.println ""
        // 输出注释
        if (isNotEmpty(it.commoent)) {
    
    
            out.println "\t/**"
            out.println "\t * ${it.commoent.toString()}"
            out.println "\t */"
            out.println "\t@ApiModelProperty(value = \"${it.commoent.toString()}\")"
        }
        if (it.name == "id") {
    
    
            out.println "\t@Id"
            out.println "\t@GeneratedValue(generator=\"JDBC\")"
        } else {
    
    
            if (it.annos != "") out.println "   ${it.annos.replace("[@Id]", "")}"
        }

        // 输出成员变量
        out.println "\tprivate ${it.type} ${it.name};"
    }

    out.println ""
    out.println "}"
}

/**
 * dao生成
 * @param out 输出流
 * @param className 类名
 * @return
 */
def mapper(out, className) {
    
    
    out.println "package $packageName" + ".dao;"
    out.println ""
    out.println "import $packageName" + ".entity.$className;"
    out.println ""
    out.println "/**\n" +
            " * @Description  \n" +
            " * @Author: hyy\n" +
            " * @Date " + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + " \n" +
            " */"
    out.println "public interface $className" + "Mapper {"
    out.println "}"
}

/**
 * service生成
 * @param out 输出流
 * @param className 类名
 * @return
 */
def service(out, className) {
    
    
    out.println "package $packageName" + ".service;"
    out.println ""
    out.println "/**\n" +
            " * @Description  \n" +
            " * @Author: hyy\n" +
            " * @Date " + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + " \n" +
            " */"
    out.println "public interface $className" + "Service {"
    out.println "}"
}

/**
 * serviceImpl生成
 * @param out 输出流
 * @param className 类名
 * @return
 */
def impl(out, className) {
    
    
    out.println "package $packageName" + ".service.impl;"
    out.println ""
    out.println "import $packageName" + ".dao." + "$className" + "Mapper;"
    out.println "import $packageName" + ".service." + "$className" + "Service;"
    out.println "import org.springframework.stereotype.Service;"
    out.println ""
    out.println "import javax.annotation.Resource;"
    out.println ""
    out.println "/**\n" +
            " * @Description  \n" +
            " * @Author: hyy\n" +
            " * @Date " + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + " \n" +
            " */"
    out.println "@Service"
    out.println "public class $className" + "ServiceImpl implements $className" + "Service {"
    out.println ""
    out.println "\t@Resource"
    out.println "\tprivate $className" + "Mapper " + Case.LOWER.apply(className[0]) + className[1..-1] + "Mapper;"
    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 comm = [
                colName : col.getName(),
                name    : javaName(col.getName(), false),
                type    : typeStr,
                commoent: col.getComment(),
                annos   : "\t@Column(name = \"" + col.getName() + "\" )"]
        if ("id".equals(Case.LOWER.apply(col.getName())))
            comm.annos += ["@Id"]
        fields += [comm]
    }
}

// 处理类名(主要是区除前缀,改成驼峰命名)
def javaClassName(str, capitalize) {
    
    
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect {
    
     Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")

    // 去除开头的tb
    s = s[2..-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
}

Générer un fichier

Faites un clic droit sur la table, puis cliquez dans l'ordre selon la figure suivante, faites attention au dernier pour sélectionner le fichier groovy créé précédemment
Insérez la description de l'image ici

Le message suivant apparaît, sélectionnez le répertoire du fichier généré
Insérez la description de l'image ici

Après avoir cliqué sur OK, le fichier est généré avec succès, la page se présente comme suit et le fichier généré se trouve dans la zone rouge.
Remarque:

  • S'il y a un fichier avec le même nom, il sera remplacé directement
  • Si les dossiers dao, entity, service et impl n'existent pas, ils seront créés automatiquement
    Insérez la description de l'image ici

Je suppose que tu aimes

Origine blog.csdn.net/huangge1199/article/details/113254919
conseillé
Classement