idea实现快速根据表创建实体第⼀步使⽤idea连上数据库
第⼆步选择需要创建实体的表
选择这个创建的实体是没有注解的
需要注解的话需要在
创建这样⼀个⽂件
⽂件的内容
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)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) }
replaceall()
}
/
/ 获取包所在⽂件夹路径
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 javax.persistence.Column;"
out.println "import javax.persistence.Entity;"
out.println "import javax.persistence.Table;"
out.println "import java.io.Serializable;"
out.println "import lombok.Getter;"
out.println "import lombok.Setter;"
out.println "import lombok.ToString;"
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" +
" * @Author  Hunter\n" +
" * @Date "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
" */"
out.println ""
out.println "@Setter"
out.println "@Getter"
out.println "@ToString"
out.println "@Entity"
out.println "@Table ( name =\""+Name() +"\" )"
out.println "public class $className  implements Serializable {"
out.println ""
out.println ""
out.println genSerialID()
fields.each() {
out.println ""
// 输出注释
if (isNotEmpty(itmoent)) {
out.println "\t/**"
out.println "\t * ${String()}"
out.println "\t */"
}
if (it.annos != "") out.println "  ${place("[@Id]", "")}"
// 输出成员变量
out.println "\tprivate ${it.type} ${it.name};"
}
// 输出get/set⽅法
//    fields.each() {
//        out.println ""
/
/        out.println "\tpublic ${it.type} get${it.name.capitalize()}() {"
//        out.println "\t\treturn this.${it.name};"
//        out.println "\t}"
//        out.println ""
//
//        out.println "\tpublic void set${it.name.capitalize()}(${it.type} ${it.name}) {"
//        out.println "\t\tthis.${it.name} = ${it.name};"
//        out.println "\t}"
//    }
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: "\t@Column(name = \""+Name()+"\" )"]
if("id".equals(Case.LOWER.Name())))
comm.annos +=["@Id"]
fields += [comm]
}
}
// 处理类名(这⾥是因为我的表都是以t_命名的,所以需要处理去掉⽣成类名时的开头的T,// 如果你不需要那么请查⽤到了 javaName这个⽅法的地⽅修改为 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() }
//            .join("").replaceAll(/[^\p{javaJavaIdentifierPart}]/, "_")
//    capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
//    capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
def s = com.deStyle.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 && String().trim().length() > 0
}
static String changeStyle(String str, boolean toCamel){
if(!str || str.size() <= 1)
return str
if(toCamel){
String r = LowerCase().split('_').collect{cc -> Case.LOWER.apply(cc).capitalize()}.join('')        return r[0].toLowerCase() + r[1..-1]
}else{
str = str[0].toLowerCase() + str[1..-1]
llect{cc -> ((char)cc).isUpperCase() ? '_' + cc.toLowerCase() : cc}.join('')
}
}
static String genSerialID()
{
return "\tprivate static final long serialVersionUID =  "+Math.abs(new Random().nextLong())+"L;" }
然后选择表,选择⾃⼰定义的groovy⽂件即可
当然需要在pom⽂件中添加
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
<!-- set,get注解实现-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
⽀持注解

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