根据表结构自动生成dao层代码
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import java.time.LocalDate
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
// 这里改包名
packageName = "com.sample;"
typeMapping = [
(~/(?i)bigint/) : "long",
(~/(?i)int/) : "int",
(~/(?i)tinyint/) : "int",
(~/(?i)float|double|decimal|real/): "double",
(~/(?i)datetime/) : "Date",
// (~/(?i)datetime|timestamp/) : "java.sql.Timestamp",
// (~/(?i)date/) : "java.sql.Date",
// (~/(?i)time/) : "java.sql.Time",
(~/(?i)/) : "String"
]
// 上面用到类和它的导入路径的之间的映射
importMap = [
"Date" : "java.util.Date",
]
// 导入路径列表,下面引用的时候会去重,也可以直接声明成一个 HashSet
importList = []
// 弹出选择文件的对话框
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}
interfaceName = ""
def generate(table, dir) {
def className = javaName(table.getName(), true)
interfaceName = className + "DAO"
def fields = calcFields(table)
new File(dir, className + "DAO.java").withPrintWriter { out -> generate(out, className, fields,table) }
}
// 从这里开始,拼interface的具体代码
def generate(out, className, fields, table) {
out.println "package $packageName"
out.println ""
// 引入所需的包
out.println("import net.paoding.rose.jade.annotation.DAO;")
out.println("import net.paoding.rose.jade.annotation.ReturnGeneratedKeys;")
out.println("import net.paoding.rose.jade.annotation.SQL;")
// 去重后导入列表
importList.unique().each() { pkg ->
out.println "import " + pkg + ";"
}
out.println ""
// 添加类注释
out.println "/**"
// 如果添加了表注释,会加到类注释上
if (isNotEmpty(table.getComment())) {
out.println " * " + table.getComment() + "--dao层"
}
out.println " *"
out.println " * @author liwenxing"
out.println " * @date " + LocalDate.now()
out.println " */"
out.println "@DAO"
out.println "public interface " + interfaceName + "{"
out.println ""
//常量定义
out.println "String TABLE_NAME = " + "\"" + table.getName() + "\";"
out.print "String INSERT_COLUMNS = \""
int i = 0;
fields.each() {
if (!it.name.equals("id")) {
i++;
if (i>1) {
out.print(",")
}
out.print(it.tableField)
}
}
out.println("\";")
out.println("String SELECT_COLUMNS = \"id,\" + INSERT_COLUMNS;")
out.print "String INSERT_VALUE_COLUMNS = \""
int j = 0;
fields.each() {
if (!it.name.equals("id")) {
j++;
if (j>1) {
out.print(",")
}
out.print(":1."+it.name)
}
}
out.println("\";")
out.println("String SELECT_PREFIX = \"select \" + SELECT_COLUMNS + \" from \" + TABLE_NAME + \" where \";")
//insert语句
out.println("")
out.println("")
out.println("@SQL(\"insert into \" + TABLE_NAME + \"(\" + INSERT_COLUMNS + \") values(\" + INSERT_VALUE_COLUMNS + \")\")")
out.println("@ReturnGeneratedKeys")
out.println("long insert(" + className + " tableInfo);")
//根据id查询
out.println("")
out.println("@SQL(SELECT_PREFIX +\"id=:1\")")
out.println(className + " getByPK(long id);")
//查询
out.println("")
out.println("String QUERY_CONDITION = \" where 1=1 \"")
fields.each() {
out.println("+ \" #if(:1." + it.name + "!=null){ and " + it.tableField + "=:1." + it.name + " }\"")
}
out.println(";")
//查询全部
out.println("//查询全部")
out.println("@SQL(SELECT_PREFIX + QUERY_CONDITION)")
out.println("List<" + className + "> queryAll(" + className + "QueryParam param);")
//查询count
out.println("//count")
out.println("@SQL(\" select count(1) from \" + TABLE_NAME + QUERY_CONDITION)")
out.println("List<" + className + "> queryCount(" + className + "QueryParam param);")
//分页查询
out.println("")
out.println("//分页查询")
out.println("@SQL(SELECT_PREFIX + QUERY_CONDITION")
out.println("+ \" order by id desc limit :2.firstRecord,:2.pageSize\"")
out.println(")")
out.println("List<" + className + "> queryByPage(" + className + "QueryParam param, PageQueryParam page);")
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 += [[
tableField : col.getName(),
name : javaName(col.getName(), false),
type : typeStr,
annos: ""]]
}
}
def isNotEmpty(content) {
return content != null && content.toString().trim().length() > 0
}
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]
}