1,database窗口

view---Tool windows----databse

2,添加mysql的database

3,填写数据库信息

4,创建导出模块,选中表右键

右键新建Generate MyPOJOs.groovy文件

bean模板代码如下

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.achievement.manager.model.sysconfig;"
typeMapping = [
        (~/(?i)int/)                      : "int",
        (~/(?i)float|double/)             : "java.math.BigDecimal",
        (~/(?i)decimal|real/)             : "java.math.BigDecimal",
        (~/(?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 className = javaName(table.getName(), true)
    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) }
}

def generate(out, className, fields) {
    out.println "package $packageName"
    out.println "import java.io.Serializable;"
    out.println ""
    out.println "public class $className implements Serializable{"
    out.println ""
    fields.each() {
        if (isNotEmpty(it.commoent)) {
            out.println ""

            out.println "  /**${it.commoent}**/"
        }
        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: ""]]
    }*/
    //非驼峰
    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 : 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
}


dao的模板如下

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
 */
//生成dao文件包名
packageName = "com.achievement.manager.mapper.sysconfig;"
//实体类包名
beanPackageName = "com.achievement.manager.model.sysconfig."
typeMapping = [
        (~/(?i)int/)                      : "int",
        (~/(?i)float|double/)             : "double",
        (~/(?i)decimal|real/)             : "java.math.BigDecimal",
        (~/(?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 className = javaName(table.getName(), true)
    def fields = calcFields(table)
    PrintWriter output = new PrintWriter(new OutputStreamWriter(new FileOutputStream( new File(dir, className + "Mapper.java")), "utf-8"))
    output.withPrintWriter{ out -> generate(out, table.getName() , className, fields) }
}

def generate(out, tableName,  className, fields) {
    out.println "package $packageName"
    out.println ""
    out.println "import java.util.List;"
    out.println "import ${beanPackageName}${className};"
    out.println "import org.apache.ibatis.annotations.Delete;"
    out.println "import org.apache.ibatis.annotations.Select;"
    out.println ""
    out.println "public interface ${className}Mapper {"
    out.println ""

    //新增
    out.println "\t/** "
    out.println "\t * insert ${tableName}"
    out.println "\t * @param ${tableName}"
    out.println "\t */"
    out.println "\tpublic void insert_${tableName}(${className} ${tableName});"
    out.println ""

    //更新
    out.println "\t/** "
    out.println "\t * update ${tableName}"
    out.println "\t * @param ${tableName}"
    out.println "\t */"
    out.println "\tpublic void update_${tableName}(${className} ${tableName});"
    out.println ""

    //删除
    out.println "\t/** "
    out.println "\t * delete "
    out.println "\t * @param ${fields[0].name}"
    out.println "\t */"
    out.println "\t@Delete(\"delete from  ${tableName} where ${fields[0].name} = #{${fields[0].name}}\")"
    out.println "\tpublic void deleteById(${fields[0].type} ${fields[0].name});"
    out.println ""

    //查找
    out.println "\t/** "
    out.println "\t * select"
    out.println "\t * @param ${fields[0].name}"
    out.println "\t * @return"
    out.println "\t */"
    out.println "\t@Select(\"select t.* from ${tableName} t where t.${fields[0].name} = #{${fields[0].name}}\")"
    out.println "\tpublic ${className} selectById(${fields[0].type} ${fields[0].name});"
    out.println ""

    //列表查询
    out.println "\t/** "
    out.println "\t * select list"
    out.println "\t * @param ${tableName}"
    out.println "\t * @return"
    out.println "\t */"
    out.println "\tpublic List<${className}> select_${tableName}(${className} ${tableName});"
    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: ""]]
    }*/
    //非驼峰
    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 : 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
}


xml模板如下

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
 */
//xml包名
packageName = "com.mdpd.manager.mapper.sysconfig."
//实体类包名  如果实体类包名为空的话,必须在mybatis-config.xml配置文件中填写实体类全路径的别名
beanPackageName = "com.mdpd.manager.model.sysconfig."
//数据库字段类型
typeMapping_db = [
        (~/(?i)int/)                      : "",
        (~/(?i)float|double/)             : "",
        (~/(?i)decimal|real/)             : ",jdbcType=DECIMAl",
        (~/(?i)datetime|timestamp|date/)  : ",jdbcType=TIMESTAMP",
        (~/(?i)time/)                     : ",jdbcType=TIME",
        (~/(?i)/)                         : ""
]

//java字段类型
typeMapping_ja = [
        (~/(?i)int/)                      : "int",
        (~/(?i)float|double/)             : "double",
        (~/(?i)decimal|real/)             : "java.math.BigDecimal",
        (~/(?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 className = javaName(table.getName(), true)
    def fields = calcFields(table)
    PrintWriter output = new PrintWriter(new OutputStreamWriter(new FileOutputStream( new File(dir, className + "Mapper.xml")), "utf-8"))
    output.withPrintWriter { out -> generate(out, table.getName(), className, fields) }
}

def generate(out, tableName, className , fields) {
    out.println "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
    out.println "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\" >"
    out.println "<mapper namespace=\"${packageName}${className}Mapper\">"
    out.println ""

    //新增
    out.println "\t<insert id=\"insert_${tableName}\" parameterType=\"${beanPackageName}${className}\" useGeneratedKeys=\"true\" keyProperty=\"${fields[0].name}\">"
    out.println "\t\tinsert into ${tableName} "
    out.println "\t\t\t("
    fields.eachWithIndex{
        it , i ->
            if (i > 0){
                out.println  i + 1  == fields.size()  ?  "\t\t\t\t${it.name}" : "\t\t\t\t${it.name},"
            }
    }
    out.println "\t\t\t)"

    out.println "\t\t\tvalues"
    out.println "\t\t\t("
    fields.eachWithIndex{
        it , j ->
            if(j > 0){
                out.println j + 1 == fields.size() ? "\t\t\t\t#{${it.name}${it.type}}" : "\t\t\t\t#{${it.name}${it.type}},"
            }
    }
    out.println "\t\t\t)"

    out.println "\t</insert>"
    out.println ""


    //更新
    out.println "\t<update id=\"update_${tableName}\" parameterType=\"${beanPackageName}${className}\">"
    out.println "\t\tupdate ${tableName} set"
    fields.eachWithIndex{
        it , i ->
            out.println  i + 1  == fields.size()  ?  "\t\t\t\t${it.name} = #{${it.name}${it.type}}" : "\t\t\t\t${it.name} = #{${it.name}${it.type}},"
    }
    out.println "\t\twhere ${fields[0].name} = #{${fields[0].name}}"
    out.println "\t</update>"
    out.println ""

    //删除和查找移到了dao文件里面了,根据注解写简单的sql语句
    //删除
    //out.println "\t<delete id=\"deleteById\" parameterType=\"${fields[0].type_ja}\">"
    //out.println "\t\tdelete from  ${tableName} where ${fields[0].name} = #{${fields[0].name}}"
    //out.println "\t</delete>"
    //out.println ""

    //查找
    //out.println "\t<select id=\"selectById\" parameterType=\"${fields[0].type_ja}\" resultType=\"${beanPackageName}${className}\">"
    //out.println "\t\tselect t.* from ${tableName} t where t.${fields[0].name} = #{${fields[0].name}}"
    //out.println "\t</select>"
    //out.println ""

    //查找列表
    out.println "\t<select id=\"select_${tableName}\" parameterType=\"${beanPackageName}${className}\" resultType=\"${beanPackageName}${className}\">"
    out.println "\t\tselect t.* from ${tableName} t "
    out.println "\t</select>"
    out.println ""


    out.println "</mapper>"
}

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: ""]]
    }*/
    //非驼峰
    DasUtil.getColumns(table).reduce([]) { fields, col ->
        def spec = Case.LOWER.apply(col.getDataType().getSpecification())
        def typeStr_db = typeMapping_db.find { p, t -> p.matcher(spec).find() }.value
        def typeStr_ja = typeMapping_ja.find { p, t -> p.matcher(spec).find() }.value
        fields += [[
                           name : col.getName(),
                           type : typeStr_db,
                           type_ja : typeStr_ja,
                           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
}


 

5,导出带注释的bean文件

选择表右键选择刚刚新建的模板,再选择导出的文件夹目录

 

更多推荐