Idea通过数据库表⽣成实体类(⾃定义)
idea真是个好东西,可以连接数据库然后通过数据库的表⾃动⽣成实体类,可以使⽤idea⾃带的,也可以按⾃⼰的想法去⽣成实体类。下⾯我们⼀起来操作⼀遍(以2019.2版本)
第⼀步,我们先⽤idea连接数据库
如果连接失败,可以试着在URL后⾯加上 ?serverTimezone=GMT
第⼆步,定义好⽣成规则
然后把以下代码复到新建的 vy ⽂件中
import com.del.DasTable
import com.del.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import java.io.*
SimpleDateFormat
/*
* Available context bindings:
*  SELECTION  Iterable<DasObject>
*  PROJECT    project
*  FILES      files helper
*/
packageName = ""
typeMapping = [
(~/(?i)tinyint|smallint|mediumint/)      : "Integer",
(~/(?i)int/)                            : "Long",
(~/(?i)bool|bit/)                        : "Boolean",
(~/(?i)float|double|decimal|real/)      : "Double",
(~/(?i)datetime|timestamp|date|time/)    : "Date",
(~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream",
(~/(?i)/)                                : "String"
]
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { generate(it, dir) }
}
def generate(table, dir) {
def className = Name(), true)
def fields = calcFields(table)
packageName = getPackageName(dir)
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "UTF-8"))  printWriter.withPrintWriter {out -> generate(out, className, fields,table)}
//    new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields,table) }
}
// 获取包所在⽂件夹路径
def getPackageName(dir) {
String().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}
def generate(out, className, fields,table) {
out.println "package $packageName"
out.println ""
out.println "import lombok.Data;"
out.println "import org.hibernate.annotations.DynamicUpdate;"
out.println "import org.hibernate.annotations.GenericGenerator;"
out.println "import org.hibernate.annotations.UpdateTimestamp;"
out.println "import javax.persistence.*;"
Set types = new HashSet()
fields.each() {
types.pe)
}
if (ains("Date")) {
out.println "import java.util.Date;"
}
if (ains("InputStream")) {
out.println "import java.io.InputStream;"
}
out.println ""
out.println "/**\n" +
" * @Description  \n" +
replaceall()
" * @Author  Henry\n" +
" * @Date "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +          " */"
out.println ""
out.println "@Entity"
out.println "@DynamicUpdate"
out.println "@Data"
out.println "@Table ( name =\""+Name() +"\" )"
out.println "public class $className  {"
out.println ""
fields.each() {
out.println ""
/
/ 输出注释
if (isNotEmpty(itmoent)) {
out.println "\t/** ${String()} */"
}
if (it.annos != "") out.println "  ${place("[@Id]", "")}"
// 输出成员变量
out.println "\tprivate ${it.type} ${it.name};"
}
out.println ""
out.println "}"
}
def calcFields(table) {
def spec = Case.LOWER.DataType().getSpecification())
def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
def comm =[
colName : Name(),
name :  Name(), false),
type : typeStr,
commoent: Comment(),
annos: ""]
if("id".equals(Case.LOWER.Name())))
comm.annos += "\t@Id\n" +
"\t@GenericGenerator(name=\"systemUUID\",strategy=\"uuid\")\n" +
"\t@GeneratedValue(generator=\"systemUUID\")"
fields += [comm]
}
}
// 处理类名(这⾥是因为我的表都是以t_命名的,所以需要处理去掉⽣成类名时的开头的T,// 如果你不需要那么请查⽤到了 javaClassName这个⽅法的地⽅修改为 javaName 即可)def javaClassName(str, capitalize) {
def s = com.deStyle.NameUtil.splitNameIntoWords(str)
.collect { Case.LOWER.apply(it).capitalize() }
.join("")
.replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
// 去除开头的T  developer.51cto/art/200906/129168.htm
s = s[1..s.size() - 1]
capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
def javaName(str, capitalize) {
//    def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。