IDEA的DATABASE自定义生成POJO、MAPPER、DAO(groovy)

利用表结构自动生成基础代码

众所周知,我是一位很懒 善于发现的程序媛,这个用了很久的脚本自动生成代码,自由度极高,墙裂推荐!!!家人们!!一定要试试!!
在这里插入图片描述

生成POJO

import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil


packageName = ""
//数据库类型对应java数据类型,可以自己调节,比如tinyint有人喜欢转成boolean
typeMapping = [
        (~/(?i)bigint/)                          : "BigInteger",
        (~/(?i)bool|bit/)                        : "Boolean",
        (~/(?i)tinyint|smallint|mediumint|int/)  : "Integer",
        (~/(?i)decimal/)                         : "BigDecimal",
        (~/(?i)float|double|decimal|real/)       : "Double",
        (~/(?i)datetime|timestamp|date|time/)    : "Date",
        (~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream",
        (~/(?i)/)                                : "String"
]
//复制以下代码,你就能发现我抄的谁的代码(〃'▽'〃)
FILES.chooseDirectoryAndSave("xuan wo!", "look look pojo!!!") { dir ->
  SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
  def className = javaName(table.getName(), true)
  def fields = calcFields(table)
  packageName = getPackageName(dir)
  //可以设置后缀,如Entity.java,加上utf-8防止乱码
  new File(dir, className + ".java").withPrintWriter("UTF-8") { out -> generate(out, className, fields, table) }
}

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

//以下正文要显示的格式内容,都可以自己调整
def generate(out, className, fields, table) {
 // def date = new Date().format("yyyy-MM-dd hh:mm")
  out.println "package $packageName"
  out.println ""
  //这个是我自己要用的注解@Data
  out.println "import lombok.Data;"
  out.println ""
  //这个是我自己要用的序列化,不用的可以不要
  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("BigInteger")) {
    out.println "import java.math.BigInteger;"
  }
  if (types.contains("BigDecimal")) {
    out.println "import java.math.BigDecimal;"
  }
  out.println ""
  out.println ""
  out.println "@Data"
  out.println "public class $className implements Serializable {"
  out.println ""
  out.println genSerialID()
  out.println ""
  fields.each() {

    if (it.annos != ""){
      out.println "\t${it.annos}"}

    //输出注释
    if (isNotEmpty(it.comment)) {
    out.println "\t/** ${it.comment} */"}

    out.println "\tprivate ${it.type} ${it.name};"
    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,
                 comment: col.getComment(), // 获取注释
                 annos: ""]]
  }
}

// 处理类名(数据库表名要怎么转换成POJO名字,自己看着处理)
// 下面这个方法(javaClassName)好像不需要,但是我不知道为什么还留着。。。
def javaClassName(str, capitalize) {
  def s = str.split(/[^\p{Alnum}]/).collect { def s = Case.LOWER.apply(it).capitalize() }.join("")
  s = s[1..s.size() - 1]
  capitalize ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

//处理字段名
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
}

static String genSerialID()
{
  return "\tprivate static final long serialVersionUID =  "+Math.abs(new Random().nextLong())+"L;"
}

生成DAO

package src

import com.google.common.base.Utf8
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil


/**********************这里要自己修改*******************/
packageName = "cn.****.****.mapper"
pojoPackageName = "cn.****.****.model" //pojoPackageName 这个要和上一步pojo放的位置一样
/**********************这里要自己修改*******************/


FILES.chooseDirectoryAndSave("xuan wo!", "look look dao!!!") { dir ->
  SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
  def baseName = javaName(table.getName(), true)
  //自定义类名
  new File(dir, "I" + baseName + "Mapper.java").withPrintWriter("utf-8") { out -> generateInterface(out, baseName) }
}

def generateInterface(out, baseName) {
 // def date = new Date().format("yyyy-MM-dd hh:mm")
  out.println "package $packageName;"
  out.println ""
  out.println "import $pojoPackageName.${baseName};" // 需手动配置
  out.println "import org.apache.ibatis.annotations.Param;"
  out.println "import org.springframework.stereotype.Repository;"
  out.println ""
  out.println "import java.math.BigInteger;"
  out.println "import java.util.List;"
  out.println ""
  out.println "@Repository"
  out.println "public interface I${baseName}Mapper {" // 可自定义
  out.println ""
  out.println "\tint insertSingle(${baseName} entity);"
  out.println "\t"
  //想要什么方法自己加
  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]
}

生成MAPPER

package src

import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

// tableName(key) : [mapper(imapper),entity(dto)]
typeMapping = [
        (~/(?i)int/)                      : "INTEGER",
        (~/(?i)float|double|decimal|real/): "DOUBLE",
        (~/(?i)datetime|timestamp/)       : "TIMESTAMP",
        (~/(?i)date/)                     : "TIMESTAMP",
        (~/(?i)time/)                     : "TIMESTAMP",
        (~/(?i)/)                         : "VARCHAR"
]

// ***********************包名需手动填写************************
iMapperPackage = "cn.****.****.mapper"
pojoPackage = "cn.****.****.model"
// ************************************************************

FILES.chooseDirectoryAndSave("xuan wo!", "look look mapper!!!") { dir ->
  SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
  def baseName = mapperName(table.getName(), true)
  def fields = calcFields(table)
  new File(dir, baseName + "Mapper.xml").withPrintWriter { out -> generate(table, out, baseName, fields) }
}

def generate(table, out, baseName, fields) {
  def baseResultMap = 'resultMap'
  def base_Column_List = 'Base_Column_List'
  //def date = new Date().format("yyyy/MM/dd")
  def tableName = table.getName()

  def imapper = iMapperPackage + ".I${baseName}Mapper"
  def pojo = pojoPackage + ".${baseName}"

  out.println mappingsStart(imapper)
  out.println ""
  out.println '''   <!-- Database Mapping -->'''
  out.println resultMap(baseResultMap, pojo, fields)
  out.println sql(fields, base_Column_List)
  out.println MyInsert(baseName, tableName, fields, pojo)
  //嘿 下面的代码自己研究吧。。我就不剧透了
 // out.println MySelectById(baseName,tableName, fields, baseResultMap, base_Column_List)
 // out.println MySelectList(baseName,tableName, fields, pojo, base_Column_List, baseResultMap)
 // out.println MyUpdateById(baseName,tableName, fields, pojo)
  out.println mappingsEnd()

}

static def resultMap(baseResultMap, pojo, fields) {

  def inner = ''
  fields.each() {
    inner += '\t\t<result column="' + it.sqlFieldName  + '" property="' + it.name + '"/>\n'
  }

  return '''\t<resultMap id="''' + baseResultMap + '''" type="''' + pojo + '''">\n''' + inner + '''\t</resultMap>'''
}

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 += [[
                       comment     : col.getComment(),
                       name        : mapperName(col.getName(), false),
                       sqlFieldName: col.getName(),
                       type        : typeStr,
                       annos       : ""]]
  }

}

def mapperName(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]
}

// ------------------------------------------------------------------------ mappings
static def mappingsStart(mapper) {
  return '''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="''' + mapper + '''">
'''
}

// ------------------------------------------------------------------------ mappings
static def mappingsEnd() {
  return '''</mapper>'''
}


// ------------------------------------------------------------------------ MyInsert
static def MyInsert(baseName, tableName, fields, parameterType) {

  return '''
    <!-- 保存 -->
    <insert id="insertSingle" useGeneratedKeys="true" keyColumn="ID" keyProperty="id">
        INSERT INTO ''' + tableName.toUpperCase() + '''(''' + columnForCommonInsert(fields) + ''')
        VALUES(''' + columnValueForCommonInsert(fields) + ''')
    </insert>
'''

}



// ------------------------------------------------------------------------ sql
static def sql(fields, base_Column_List) {
  def str = '''\t<sql id="''' + base_Column_List + '''">
        @inner@
    </sql> '''

  def inner = ''
  fields.each() {
    inner += ('' + it.sqlFieldName + ',')
  }

  return str.replace("@inner@", inner.substring(0, inner.length() - 1))

}


//下面是一些数据处理的方法
static def testNotNullStrWhereWithoutIdForUpdate(fields) {
  def inner = ''
  fields.each {
    if (it.sqlFieldName.toUpperCase() != "ID"){
      inner += '''\t\t\t<if test="''' + it.name + ''' != null">  ''' + it.sqlFieldName + ''' = #{''' + it.name + '''}, </if>\n'''
    }
  }

  return inner
}

static def testNotNullStrWhereWithoutIdForSelect(fields) {
  def inner = ''
  fields.each {
    if (it.sqlFieldName.toUpperCase() != "ID"){
      inner += '''\t\t\t<if test="''' + it.name + ''' != null">  AND ''' + it.sqlFieldName + ''' = #{''' + it.name + '''} </if>\n'''
    }
  }

  return inner
}

static def testNotNullStrWhere(fields) {
  def inner = ''
  fields.each {
    inner += '''\t\t\t<if test="''' + it.name + ''' != null">  ''' + it.sqlFieldName + ''' = #{''' + it.name + '''}, </if>\n'''
  }

  return inner
}

static def testNotNullStrSet(fields) {
  def inner = ''
  fields.each {
    inner += '''
        <if test="''' + it.name + ''' != null">
            #{''' + it.name + '''},
        </if>\n'''
  }

  return inner
}

static def testNotNullStr(fields) {
  def inner1 = ''
  fields.each {
    inner1 += '''
        <if test = "''' + it.name + ''' != null" >
        \t''' + it.sqlFieldName + ''',
        </if>\n'''
  }

  return inner1
}

static def columnWithoutId(fields) {
  def inner2 = ''
  fields.each {
    if(it.sqlFieldName != "ID" && it.sqlFieldName != "Id" && it.sqlFieldName != "id") {

      inner2 +=
              it.sqlFieldName + (it != fields.last()?''',''':'''''')
    }
  }

  return inner2
}
static def columnForCommonInsert(fields) {
  def inner2 = ''
  fields.each {
    if(it.sqlFieldName != "ID" && it.sqlFieldName != "Id" && it.sqlFieldName != "id"
            && it.sqlFieldName != "create_time"
            && it.sqlFieldName != "update_time"
            && it.sqlFieldName != "update_user") {

      inner2 +=
              it.sqlFieldName + (it.sqlFieldName != "create_user"?''',''':'''''')
    }
  }


  return inner2
}

static def columnValueForCommonInsert(fields) {
  def inner3 = ''
  fields.each {
    if(it.sqlFieldName != "ID" && it.sqlFieldName != "Id" && it.sqlFieldName != "id"
            && it.sqlFieldName != "create_time"
            && it.sqlFieldName != "update_time"
            && it.sqlFieldName != "update_user") {

      inner3 += '''#{''' +
              it.name + (it.sqlFieldName != "create_user"?'''},''':'''}''')
    }
  }

  return inner3
}

然后玩儿去吧!

在这里插入图片描述
后面就不多说了,有手就行!芜湖~~

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值