说明:
以下内容是根据idea自带的scripted Extentions 中的 Generate POJOs.groovy 改造而来,可以自动生成xml、dao、数据源文件共计5个文件,可以自动匹配商品中心的需求【根据门店、大区、log等自动添加多数据源注解】,如不符合要求可根据groovy语法自行改造。
遗留问题:
步骤:
打开idea连接databases:
打开mysql连接:
填写数据库信息:
出现如图信息,如果发现缺库,右键数据库上properties,勾选all schema:
打开如下图所示:
选择需要导入的路径:
自动生成如下文件:
代码为适应公司结构专门定制,可能不适合通用代码,请自行修改。
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import javax.swing.text.html.parser.Entity
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
packageName = "com.demo.soa.xx.center.model"
packageNameDao = "com.demo.soa.xx.center.dal.dao"
packageNameDaoXml = "com.demo.soa.xx.center.dal.dao"
packageNameService = "com.demo.soa.xx.center.service.core"
packageNameServiceImpl = "com.demo.soa.xx.center.service.core.impl"
typeMapping = [
(~/(?i)bigint/) : "Long",
(~/(?i)int/) : "Integer",
(~/(?i)float|double|decimal|real/): "BigDecimal",
(~/(?i)datetime|timestamp/) : "Date",
(~/(?i)date/) : "Date",
(~/(?i)time/) : "Date",
(~/(?i)/) : "String"
]
jdbcTypeMapping = [
(~/(?i)bigint/) : "BIGINT",
(~/(?i)int/) : "INTEGER",
(~/(?i)tinyint/) : "TINYINT",
(~/(?i)smallint/) : "SMALLINT",
(~/(?i)float|double|decimal|real/): "DECIMAL",
(~/(?i)datetime|timestamp/) : "TIMESTAMP",
(~/(?i)date/) : "TIMESTAMP",
(~/(?i)time/) : "TIMESTAMP",
(~/(?i)/) : "VARCHAR"
]
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)
className = clearStoreAndAreaTableName(className as String)
def fields = calcFields(table)
new File(dir, className + ".java").withPrintWriter("utf-8") { out -> generate(out, className, fields) }
new File(dir, className + "Dao.java").withPrintWriter("utf-8") { out -> generateInterface(out, className) }
new File(dir, className + "Dao.xml").withPrintWriter("utf-8") { out -> generateXml(table, out, className, fields) }
new File(dir, className + "Service.java").withPrintWriter("utf-8") { out -> generateService(table, out, className, fields) }
new File(dir, className + "ServiceImpl.java").withPrintWriter("utf-8") { out -> generateServiceImpl(table, out, className, fields) }
}
def generate(out, className, fields) {
copyRight(out)
out.println "package ${packageName};"
out.println ""
out.println ""
out.println "import lombok.Data;"
Set types = new HashSet()
fields.each() {
types.add(it.type)
}
if (types.contains("Date")) {
out.println "import java.util.Date;"
}
if (types.contains("BigDecimal")) {
out.println "import java.math.BigDecimal;"
}
out.println ""
out.println ""
doc(out)
out.println "@Data"
out.println "public class $className {"
out.println ""
fields.each() {
if (it.annos != "") out.println " ${it.annos}"
out.println " /**"
out.println " * ${it.commoent}"
out.println " */"
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 copyRight(out){
out.println "/*"
String c1 = new String(" * Copyright (C) 1997-2020 xxxx(中国)有限公司".getBytes(), "utf-8")
out.println c1
out.println " *"
out.println " * http://www.rt-mart.com"
out.println " *"
String c2 = new String(" * 版权归本公司所有,不得私自使用、拷贝、修改、删除,否则视为侵权".getBytes(), "utf-8")
out.println c2
out.println " *"
out.println " */"
out.println ""
}
def doc(out){
def date = new Date().format("yyyy/MM/dd")
out.println "/**"
out.println " * Created on $date."
out.println " *"
out.println " * @author auto generate"
out.println " */"
}
def generateInterface(out, baseName) {
copyRight(out)
out.println "package ${packageNameDao};"
out.println ""
out.println ""
out.println "import org.springframework.stereotype.Repository;"
out.println "import org.apache.ibatis.annotations.Param;"
out.println "import com.demo.soa.xx.center.dal.BaseDao;"
out.println "import ${packageName}.${baseName};"
out.println "import java.util.List;"
out.println ""
out.println ""
doc(out)
out.println "@Repository"
out.println "public interface ${baseName}Dao extends BaseDao<${baseName}> {"
out.println ""
out.println "\tList<${baseName}> selectList(${baseName} record);"
out.println ""
out.println "\tint batchUpdateById(@Param(\"entityList\")List<${baseName}> entityList);"
out.println ""
out.println "\tint batchInsertSelective(@Param(\"entityList\")List<${baseName}> entityList);"
out.println "}"
}
def generateXml(table, out, baseName, fields) {
def baseResultMap = 'BaseResultMap'
def base_Column_List = 'Base_Column_List'
def base_Where = 'Base_Where'
def base_Set = 'Base_Set'
def tableName = table.getName()
tableName = changeTableName(tableName)
def dao = packageNameDaoXml + ".${baseName}Dao"
def to = packageName + ".${baseName}"
out.println mappingsStart(dao)
out.println resultMap(baseResultMap, to, fields)
out.println sql(fields, base_Column_List)
out.println where(fields, base_Where)
out.println set(fields, base_Set)
out.println selectByPrimaryKey(tableName, fields, baseResultMap, base_Column_List)
out.println deleteByPrimaryKey(tableName, fields)
//基本不会用到可选择删除
// out.println delete(tableName, fields, to)
out.println insertSelective(tableName, fields, to)
out.println updateByPrimaryKey(tableName, fields, to, base_Set)
out.println selectList(tableName, fields, to, base_Column_List, baseResultMap, base_Where)
//todo 批量新增和修改逻辑
out.println batchInsertSelective(tableName, fields, to)
out.println batchUpdateById(tableName, fields, to)
out.println mappingsEnd()
}
def generateService(table, out, baseName, fields) {
copyRight(out)
def key = dynamicDbKey(dynamicDataSource(table.getName()))
def extend = "" == key ? " extends IBaseService<${baseName}, Integer>" : " extends IDynamicBaseService<${baseName}, Integer>"
out.println "package ${packageNameService};"
out.println ""
out.println ""
out.println "import org.springframework.stereotype.Repository;"
out.println "import ${packageName}.${baseName};"
out.println "import java.util.List;"
out.println ""
out.println ""
doc(out)
out.println "public interface ${baseName}Service ${extend}{"
out.println ""
out.println "}"
}
def generateServiceImpl(table, out, baseName, fields) {
copyRight(out)
def source = dynamicDataSource(table.getName())
def key = dynamicDbKey(source)
char[] chars = baseName.toCharArray()
chars[0] = Character.toLowerCase(chars[0])
def lowerBaseName = String.valueOf(chars)
out.println "package ${packageNameServiceImpl};"
out.println ""
out.println ""
out.println "import org.springframework.stereotype.Service;"
out.println "import org.springframework.beans.factory.annotation.Autowired;"
out.println "import com.xx.soa.common.support.datasource.DynamicDataSource;"
out.println "import com.xx.soa.constants.goods.center.Constants;"
out.println "import com.github.pagehelper.Page;"
out.println "import ${packageNameService}.${baseName}Service;"
out.println "import ${packageNameDao}.${baseName}Dao;"
out.println "import ${packageName}.${baseName};"
out.println "import java.util.List;"
out.println ""
out.println ""
doc(out)
out.println "@Service"
out.println "public class ${baseName}ServiceImpl implements ${baseName}Service {"
out.println ""
out.println "\t@Autowired"
out.println "\tprivate ${baseName}Dao ${lowerBaseName}Dao;"
out.println ""
out.println ""
out.println "\t@Override"
out.println "\t${source}"
out.println "\tpublic List<${baseName}> findAll(${key}${baseName} record) {"
out.println "\t\treturn ${lowerBaseName}Dao.selectList(record);"
out.println "\t}"
out.println ""
out.println ""
out.println "\t@Override"
out.println "\t${source}"
out.println "\tpublic int save(${key}${baseName} entity) {"
out.println "\t\treturn ${lowerBaseName}Dao.insertSelective(entity);"
out.println "\t}"
out.println ""
out.println ""
out.println "\t@Override"
out.println "\t${source}"
out.println "\tpublic ${baseName} getOne(${key}Integer id) {"
out.println "\t\treturn ${lowerBaseName}Dao.selectByPrimaryKey(id);"
out.println "\t}"
out.println ""
out.println ""
out.println "\t@Override"
out.println "\t${source}"
out.println "\tpublic int deleteById(${key}Integer id) {"
out.println "\t\treturn ${lowerBaseName}Dao.deleteByPrimaryKey(id);"
out.println "\t}"
out.println ""
out.println ""
out.println "\t@Override"
out.println "\t${source}"
out.println "\tpublic int update(${key}${baseName} entity) {"
out.println "\t\treturn ${lowerBaseName}Dao.updateByPrimaryKey(entity);"
out.println "\t}"
out.println ""
out.println ""
out.println "\t@Override"
out.println "\t${source}"
out.println "\tpublic int updateAll(${key}List<${baseName}> entityList) {"
out.println "\t\treturn ${lowerBaseName}Dao.batchUpdateById(entityList);"
out.println "\t}"
out.println ""
out.println ""
out.println "\t@Override"
out.println "\t${source}"
out.println "\tpublic int saveAll(${key}List<${baseName}> entityList) {"
out.println "\t\treturn ${lowerBaseName}Dao.batchInsertSelective(entityList);"
out.println "\t}"
//page find all
out.println ""
out.println "\t@Override"
out.println "\t${source}"
out.println "" == key ? "\tpublic Page<${baseName}> findAll(Page<${baseName}> page, ${baseName} param) {" :
"\tpublic Page<${baseName}> findAll(${key}Page<${baseName}> page, ${baseName} param) {"
out.println "\t\t// TODO Auto-generated method stub"
out.println "\t\treturn null;"
out.println "\t}"
// delete
out.println ""
out.println "\t@Override"
out.println "\t${source}"
out.println "\tpublic int delete(${key}${baseName} entity) {"
out.println "\t\t// TODO Auto-generated method stub"
out.println "\t\treturn 0;"
out.println "\t}"
//deleteByIds
out.println ""
out.println "\t@Override"
out.println "\t${source}"
out.println "\tpublic int deleteByIds(${key}List<Integer> ids) {"
out.println "\t\t// TODO Auto-generated method stub"
out.println "\t\treturn 0;"
out.println "\t}"
//deleteAll
out.println ""
out.println "\t@Override"
out.println "\t${source}"
out.println "\tpublic void deleteAll(${key}List<? extends ${baseName}> entityList) {"
out.println "\t\t// TODO Auto-generated method stub"
out.println "\t}"
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
def jdbcTypeStr = jdbcTypeMapping.find { p, t -> p.matcher(spec).find() }.value
fields += [[
name : javaName(col.getName(), false),
type : typeStr,
jdbcType : jdbcTypeStr,
commoent: col.getComment(),
sqlFieldName: col.getName(),
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]
}
static def dynamicDbKey(dynamicDataSource){
if (dynamicDataSource.contains("STORE")){
return "String storeId, "
}
if (dynamicDataSource.contains("AREA")){
return "String areaId, "
}
return ""
}
static def dynamicDataSource(tableName){
if (isLogTable(tableName)){
return "@DynamicDataSource(type = Constants.TYPE_RT_GOODS_CENTER_LOG)"
}
if (isStoreTable(tableName)){
return "@DynamicDataSource(type = Constants.TYPE_RT_GOODS_CENTER_STORE)"
}
if (isAreaTable(tableName)){
return "@DynamicDataSource(type = Constants.TYPE_RT_GOODS_CENTER_AREA)"
}
return "@DynamicDataSource(type = Constants.TYPE_RT_GOODS_CENTER_DEFAULT)"
}
static def isLogTable(tableName) {
return tableName.contains("log")
}
static def isAreaTable(tableName) {
return ["1", "2", "3", "4", "5"].contains(tableName.substring(tableName.length() - 1))
}
static def isStoreTable(tableName) {
return tableName.substring(tableName.length() - 4, tableName.length()) ==~ '[0-9]*'
}
static def clearAreaTableName(tableName) {
return tableName.substring(0, tableName.length() - 1)
}
static def clearStoreTableName(tableName) {
return tableName.substring(0, tableName.length() - 4)
}
static def clearStoreAndAreaTableName(tableName) {
return isStoreTable(tableName) ? clearStoreTableName(tableName) : (isAreaTable(tableName) ? clearAreaTableName(tableName) : tableName)
}
static def changeTableName(tableName){
isStoreTable(tableName) ? clearStoreTableName(tableName) + "#STOREID#" : (isAreaTable(tableName) ? clearAreaTableName(tableName) + "#AREAID#" : tableName)
}
static def resultMap(baseResultMap, to, fields) {
def inner = ''
fields.each() {
if ("id" == it.sqlFieldName){
return
}
inner += '\t\t<result column="' + it.sqlFieldName + '" jdbcType="' + it.jdbcType + '" property="' + it.name + '"/>\n'
}
return '''\t<resultMap id="''' + baseResultMap + '''" type="''' + to + '''">
<id column="id" jdbcType="INTEGER" property="id"/>
''' + inner + '''\t</resultMap>
'''
}
// ------------------------------------------------------------------------ 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>'''
}
// ------------------------------------------------------------------------ selectById
static def selectByPrimaryKey(tableName, fields, baseResultMap, base_Column_List) {
return '''
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="''' + baseResultMap + '''">
select
<include refid="''' + base_Column_List + '''"/>
from ''' + tableName + '''
where id = #{id}
</select>'''
}
// ------------------------------------------------------------------------ insert
static def insertSelective(tableName, fields, parameterType) {
return '''
<insert id="insertSelective" parameterType="''' + parameterType + '''">
insert into ''' + tableName + '''
<trim prefix="(" suffix=")" suffixOverrides=",">
''' + testNotNullStr(fields, "") + '''
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
''' + testNotNullStrInsert(fields, "") + '''
</trim>
</insert>
'''
}
// ------------------------------------------------------------------------ update
static def updateByPrimaryKey(tableName, fields, parameterType, base_Set) {
return '''
<update id="updateByPrimaryKey" parameterType="''' + parameterType + '''">
update ''' + tableName + '''
<include refid="''' + base_Set + '''"/>
where id = #{id}
</update>'''
}
// ------------------------------------------------------------------------ deleteById
static def deleteByPrimaryKey(tableName, fields) {
return '''
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete
from ''' + tableName + '''
where id = #{id}
</delete>'''
}
// ------------------------------------------------------------------------ delete
static def delete(tableName, fields, parameterType) {
return '''
<delete id="delete" parameterType="''' + parameterType + '''">
delete from ''' + tableName + '''
<where>
''' + testNotNullStrWhere(fields, "") + '''
</where>
</delete>'''
}
// ------------------------------------------------------------------------ selectList
static def selectList(tableName, fields, parameterType, base_Column_List, baseResultMap, base_Where) {
return '''
<select id="selectList" parameterType="''' + parameterType + '''" resultMap="''' + baseResultMap + '''">
select
<include refid="''' + base_Column_List + '''"/>
from ''' + tableName + '''
<include refid="''' + base_Where + '''"/>
order by id desc
</select>'''
}
// ------------------------------------------------------------------------ batchInsertSelective
static def batchInsertSelective(tableName, fields, parameterType) {
return '''
<insert id="batchInsertSelective" parameterType="''' + parameterType + '''">
<foreach collection="entityList" item="entity" separator=";">
insert into ''' + tableName + '''
<trim prefix="(" suffix=")" suffixOverrides=",">
''' + testNotNullStr(fields, "entity.") + '''
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
''' + testNotNullStrInsert(fields, "entity.") + '''
</trim>
</foreach>
</insert>
'''
}
// ------------------------------------------------------------------------ batchUpdateById
static def batchUpdateById(tableName, fields, parameterType) {
return '''
<update id="batchUpdateById" parameterType="''' + parameterType + '''">
<foreach collection="entityList" item="entity" separator=";">
update ''' + tableName + '''
<set>
''' + testNotNullStrSet(fields, "entity.") + '''
</set>
<where>
id = #{entity.id}
</where>
</foreach>
</update>
'''
}
// ------------------------------------------------------------------------ sql
static def sql(fields, base_Column_List) {
def str = '''\t<sql id="''' + base_Column_List + '''">
@inner@
</sql> '''
def inner = ''
fields.each() {
inner += ('\t\t' + it.sqlFieldName + ',\n')
}
return str.replace("@inner@", inner.substring(0, inner.length() - 2))
}
// ------------------------------------------------------------------------ where
static def where(fields, base_Where) {
def str = '''\t<sql id="''' + base_Where + '''">
@inner@
</sql> '''
def inner = '<where>'
inner += ('\t\t' + testNotNullStrWhere(fields, "") + ',\n')
return str.replace("@inner@", inner.substring(0, inner.length() - 2) + '\t\t</where>')
}
// ------------------------------------------------------------------------ set
static def set(fields, base_Set) {
def str = '''\t<sql id="''' + base_Set + '''">
@inner@
</sql> '''
def inner = '<set>'
inner += ('\t\t' + testNotNullStrSet(fields, "") + ',\n')
return str.replace("@inner@", inner.substring(0, inner.length() - 2) + '\t\t</set>')
}
static def testNotNullStrSet(fields, entity) {
def inner = ''
fields.each {
if (!(it.name == "id")) {
inner += '''
\t<if test="''' + entity + it.name + ''' != null">
\t''' + it.sqlFieldName + ''' = #{''' + entity + it.name + '''},
\t</if>\n'''
}
}
return inner
}
static def testNotNullStrWhere(fields, entity) {
def inner = ''
fields.each {
inner += '''
\t<if test="''' + entity + it.name + ''' != null">
\tand ''' + it.sqlFieldName + ''' = #{''' + entity + it.name + '''}
\t</if>\n'''
}
return inner
}
static def testNotNullStrInsert(fields, entity) {
def inner = ''
fields.each {
inner += '''
\t<if test="''' + entity + it.name + ''' != null">
\t#{''' + entity + it.name + '''},
\t</if>\n'''
}
return inner
}
static def testNotNullStr(fields, entity) {
def inner1 = ''
fields.each {
inner1 += '''
\t<if test = "'''+ entity + it.name + ''' != null" >
\t\t''' + it.sqlFieldName + ''',
\t</if>\n'''
}
return inner1
}
参考文献:
groovy 语法:
因篇幅问题不能全部显示,请点此查看更多更全内容