IDEA中根据MySql表生成实体类, SQL文件

IDEA中根据MySql表生成实体类, SQL文件, 同时解决了groovy输出中文乱码的问题

1. 在IDEA中创建mysql连接 [参考]

2. 创建groovy脚本 [ 参考

  (1) 选择要生成实例的表(支持多选)
  (2) 右击已选中的表 > Scripted Extensions > Go To Scripts Directory
  (3) 在左侧schema文件, 复制Generate POJOs.groovy并粘贴,改名为新脚本
  (4) 编辑新脚本, 粘贴后面备注里面的groovy脚本, 保存
  (5) 修改脚本以生成符合自己需求的文件格式

3. 使用新脚本, 生成类实例, sql文件  [ 参考 ] 

备注脚本:

  1 import com.intellij.database.model.DasTable
  2 import com.intellij.database.util.Case
  3 import com.intellij.database.util.DasUtil
  4 
  5 /*
  6  * Available context bindings:
  7  *   SELECTION   Iterable<DasObject>
  8  *   PROJECT     project
  9  *   FILES       files helper
 10  */
 11 
 12 packageName = ""
 13 typeMapping = [
 14         (~/(?i)bigint/)                   : "long",
 15         (~/(?i)int/)                      : "String",
 16         (~/(?i)float|double|decimal|real/): "String",
 17         (~/(?i)datetime|timestamp/)       : "String",
 18         (~/(?i)date/)                     : "String",
 19         (~/(?i)time/)                     : "String",
 20         (~/(?i)/)                         : "String"
 21 ]
 22 tab = "    "
 23 primaryKey = "id"
 24 
 25 FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
 26     SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
 27 }
 28 
 29 def generate(table, dir) {
 30     def className = javaName(table.getName(), true)
 31     def fields = calcFields(table)
 32     packageName = getPackageName(dir)
 33     primaryKey = findPrimaryKey(fields)
 34 
 35     printWriter(dir, className + ".java").withPrintWriter { out -> generateClass(out, className, table, fields) }
 36     printWriter(dir, "sqlMap" + className + ".xml").withPrintWriter { out -> generateSQL(out, className, table, fields) }
 37 }
 38 
 39 def printWriter(dir, fileName) {
 40     return new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, fileName)), "utf-8"))
 41 }
 42 
 43 //系统默认一般都不是utf-8
 44 def cn(text){
 45     return new String(text.getBytes(System.getProperty("file.encoding")),"utf-8");
 46 }
 47 
 48 //生成pojo类
 49 def generateClass(out, className, table, fields) {
 50     out.println "/**"
 51     out.println " * ${cn("© xx有限公司")}"
 52     out.println " * ${cn("协议说明")}"
 53     out.println " */"
 54     out.println "package $packageName"
 55     out.println ""
 56     out.println ""
 57     out.println "/**"
 58     out.println " * ${table.getComment()}"
 59     out.println " * ${cn("业务详细说明")}"
 60     out.println " */"
 61     out.println "public class $className {"
 62     out.println ""
 63     fields.each() {
 64         if (it.annos != "") out.println "  ${it.annos}"
 65         // 输出注释
 66         if (it.commoent != null && it.commoent != "") {
 67             out.println "    /**"
 68             out.println "     * ${it.commoent.toString()}"
 69             out.println "     */"
 70         }
 71         out.println "    private ${it.type} ${it.name};"
 72     }
 73     //setter, getter
 74     out.println ""
 75     fields.each() {
 76         out.println ""
 77         out.println "${tab}public ${it.type} get${it.name.capitalize()}() {"
 78         out.println "${tab}${tab}return ${it.name};"
 79         out.println "${tab}}"
 80         out.println ""
 81         out.println "${tab}public void set${it.name.capitalize()}(${it.type} ${it.name}) {"
 82         out.println "${tab}${tab}this.${it.name} = ${it.name};"
 83         out.println "${tab}}"
 84         out.println ""
 85     }
 86     out.println ""
 87     out.println "}"
 88 }
 89 
 90 //生成sql
 91 def generateSQL(out, className, table, fields) {
 92     out.println "<?xml version="1.0" encoding="UTF-8" ?>"
 93     out.println "<sqlMap namespace="${table.getName().toUpperCase()}">"
 94     out.println ""
 95     //INSERT
 96     out.println "${tab}<sql id="INSERT">"
 97     out.println "${tab}${tab}<![CDATA["
 98     out.println "${tab}${tab}${tab}INSERT INTO ${table.getName()}"
 99     out.println "${tab}${tab}${tab}("
100     fields.each() {
101         out.println "${tab}${tab}${tab}${tab}<#if ${it.javaName} ? exists > `${it.name}`${it == fields.last() ? "" : ","}</#if>"
102     }
103     out.println "${tab}${tab}${tab})"
104     out.println "${tab}${tab}${tab}VALUES("
105     fields.each() {
106         out.println "${tab}${tab}${tab}${tab}<#if ${it.javaName} ? exists > :${it.javaName}</#if>"
107     }
108     out.println "${tab}${tab}${tab})"
109     out.println "${tab}${tab}]]>"
110     out.println "${tab}</sql>"
111     out.println ""
112 
113     //UPDATE
114     out.println "${tab}<sql id="UPDATE">"
115     out.println "${tab}${tab}<![CDATA["
116     out.println "${tab}${tab}${tab}UPDATE ${table.getName()}"
117     out.println "${tab}${tab}${tab}SET"
118     fields.each() {
119         out.println "${tab}${tab}${tab}${tab}<#if ${it.javaName} ? exists > `${it.name}`=:${it.javaName}</#if>"
120     }
121     out.println "${tab}${tab}${tab}WHERE"
122     out.println "${tab}${tab}${tab}${tab}${primaryKey}=:id"
123     out.println "${tab}${tab}]]>"
124     out.println "${tab}</sql>"
125     out.println ""
126 
127     //QUERY
128     out.println "${tab}<sql id="QUERY">"
129     out.println "${tab}${tab}<![CDATA["
130     out.println "${tab}${tab}${tab}SELECT"
131     fields.each() {
132         out.println "${tab}${tab}${tab}${tab}`${it.name}`${it == fields.last() ? "" : ","}"
133     }
134     out.println "${tab}${tab}${tab}FROM ${table.getName()}"
135     out.println "${tab}${tab}${tab}WHERE 1=1"
136     fields.each() {
137         out.println "${tab}${tab}${tab}${tab}<#if ${it.javaName} ? exists > `${it.name}`=:${it.javaName}</#if>"
138     }
139     out.println "${tab}</sql>"
140     out.println ""
141 
142     //
143     out.println "</sqlMap>"
144 }
145 
146 //用反射查看类信息
147 def printInfo(out, className, table, fields) {
148     //DasUtil.isAutoGenerated(DasColumn)
149     //DasUtil.isPrimary(DasColumn)
150     //DasUtil.isIndexColumn(DasColumn)
151     out.println ""
152     out.println ""
153     printMethods(out, table.class);
154     out.println ""
155     out.println ""
156 
157     out.println "primaryKey=${primaryKey}"
158     out.println ""
159     out.println ""
160     printMethods(out, DasUtil.class);
161     out.println ""
162     out.println ""
163 }
164 
165 //查询字段
166 def calcFields(table) {
167     DasUtil.getColumns(table).reduce([]) { fields, col ->
168         def spec = Case.LOWER.apply(col.getDataType().getSpecification())
169         def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
170         fields += [[
171                            name    : col.getName(),
172                            javaName: javaName(col.getName(), false),
173                            type    : typeStr,
174                            commoent: col.getComment(),
175                            annos   : "",
176                            col     : col
177                    ]]
178     }
179 }
180 
181 //生成javaName
182 def javaName(str, capitalize) {
183     def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
184             .collect { Case.LOWER.apply(it).capitalize() }
185             .join("")
186             .replaceAll(/[^p{javaJavaIdentifierPart}[_]]/, "_")
187     capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
188 }
189 
190 //生成包名称
191 def getPackageName(dir) {
192     return dir.toString().replaceAll("\\", ".")
193             .replaceAll("/", ".")
194             .replaceAll("^.*src(\.main\.java\.)?", "") + ";"
195 }
196 
197 //通过反射查看类方法, 也可以直接查看官网psi文件api
198 def printMethods(out, clazz) {
199     clazz.declaredMethods.each() {
200         out.println(it)
201     }
202 }
203 
204 //获取主键
205 def findPrimaryCol(fields) {
206     def col
207     fields.each() {
208         if (DasUtil.isPrimary(it.col)) {
209             col = it;
210             return true;
211         }
212     }
213     return col
214 }
215 
216 //获取主键
217 def findPrimaryKey(fields) {
218     def col = findPrimaryCol(fields)
219     if (col != null) {
220         return col.name
221     }
222     return "id"
223 }
原文地址:https://www.cnblogs.com/sanshizi/p/14386072.html