今天要写一个导入功能,需要把数据库的一个表映射成一个pojo,但是这表字段不是一般的多啊。。。想了想能不能自动生成???在IDEA中点了半天发现还是可以的
下面介绍一下步骤:
第一步:找到这个图标,建立一个数据库连接
建立完成之后如下图:
第二部修改生成pojo的脚本,切换到这个视图
主要是修改包名:
把上图中的packageName修改成生成pojo存放位置的包即可
第三步:选中要生成实体类的表(可以多选),右键按下图即可生成
如果项目中使用了Lombok插件的话,可以扩展一下自带的Generate POJOs.groovy就可很快的生成我们想要形式的pojo
下面是我的这个工程结构:
这是一个典型的maven工程结构,针对maven工程,扩展的两个groovy脚本,两个脚本均可以根据选择的文件夹自动生成正确的包名
Generate POJOs For Hibernate Lombok.groovy 这个脚本用来生成Hibernate的实体类,要注意两点:1、主键名必须是“id”,2、如果表中有版本字段,那么版本字段名必须是"version",3、这脚本生成的实体类,主键生成策略没有采用自增模式,如果你的表中主键设置了自增的话,
需要稍微改动一下才可以用
1 import com.intellij.database.model.DasTable 2 import com.intellij.database.model.ObjectKind 3 import com.intellij.database.util.Case 4 import com.intellij.database.util.DasUtil 5 6 /* 7 * Available context bindings: 8 * SELECTION Iterable<DasObject> 9 * PROJECT project 10 * FILES files helper 11 */ 12 typeMapping = [ 13 (~/(?i)int/) : "long", 14 (~/(?i)float|double|decimal|real/): "double", 15 (~/(?i)datetime|timestamp/) : "java.sql.Timestamp", 16 (~/(?i)date/) : "java.sql.Date", 17 (~/(?i)time/) : "java.sql.Time", 18 (~/(?i)/) : "String" 19 ] 20 21 FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir -> 22 SELECTION.filter { 23 it instanceof DasTable && it.getKind() == ObjectKind.TABLE 24 }.each { 25 generate(it, dir) 26 } 27 } 28 29 def generate(table, dir) { 30 def className = javaName(table.getName(), true) 31 def fields = calcFields(table) 32 def tableName = table.getName() 33 def path = dir.getPath() 34 def packageName = path.substring(path.lastIndexOf("java") + 5, path.length()).replaceAll("\\", ".") 35 new File(dir, className + ".java").withPrintWriter { out -> generate(out, tableName, className, fields, packageName) } 36 } 37 38 def generate(out, tableName, className, fields, packageName) { 39 out.println "package $packageName;" 40 out.println "" 41 out.println "import lombok.Data;" 42 out.println "import org.hibernate.annotations.DynamicInsert;" 43 out.println "import org.hibernate.annotations.DynamicUpdate;" 44 out.println "import org.hibernate.annotations.GenericGenerator;" 45 out.println "" 46 out.println "import javax.persistence.*;" 47 out.println "import java.io.Serializable;" 48 out.println "" 49 out.println "@Data" 50 out.println "@Entity" 51 out.println "@Table(name = "${tableName}")" 52 out.println "@DynamicUpdate(true)" 53 out.println "@DynamicInsert(true)" 54 out.println "public class $className implements Serializable{" 55 out.println "" 56 out.println " private static final long serialVersionUID = 33163593958226L;" 57 out.println "" 58 fields.each() { 59 if (it.annos != "") out.println " ${it.annos}" 60 out.println " private ${it.type} ${it.name};" 61 out.println "" 62 } 63 out.println "}" 64 } 65 66 def calcFields(table) { 67 DasUtil.getColumns(table).reduce([]) { fields, col -> 68 def spec = Case.LOWER.apply(col.getDataType().getSpecification()) 69 def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value 70 if (col.getName().toLowerCase() == "id") { 71 fields += [[name : javaName(col.getName(), false), 72 type : typeStr, 73 annos: "@Id " + 74 " @GeneratedValue(generator = "" + table.getName() + "IDGenerator" , strategy = GenerationType.AUTO) " + 75 " @GenericGenerator(name = "" + table.getName() + "IDGenerator" , strategy = "uuid") " + 76 " @Column(name ="" + col.getName() + "")"]] 77 } else if(col.getName().toLowerCase() == "version"){ 78 fields += [[name : javaName(col.getName(), false), 79 type : typeStr, 80 annos: "@Version " + 81 " @Column(name ="" + col.getName() + "")"]] 82 }else { 83 fields += [[name : javaName(col.getName(), false), 84 type : typeStr, 85 annos: "@Column(name ="" + col.getName() + "")"]] 86 } 87 } 88 } 89 90 def javaName(str, capitalize) { 91 def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str) 92 .collect { Case.LOWER.apply(it).capitalize() } 93 .join("") 94 .replaceAll(/[^p{javaJavaIdentifierPart}[_]]/, "_") 95 capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1] 96 }
Generate POJOs For Lombok.groovy 使用lombok插件之后可以采用如下脚本生成Lombok形式的pojo
import com.intellij.database.model.DasTable import com.intellij.database.model.ObjectKind import com.intellij.database.util.Case import com.intellij.database.util.DasUtil /* * Available context bindings: * SELECTION Iterable<DasObject> * PROJECT project * FILES files helper */ packageName = "com.ryb.pojo;" typeMapping = [ (~/(?i)int/) : "long", (~/(?i)float|double|decimal|real/): "double", (~/(?i)datetime|timestamp/) : "java.sql.Timestamp", (~/(?i)date/) : "java.sql.Date", (~/(?i)time/) : "java.sql.Time", (~/(?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 = javaName(table.getName(), true) def fields = calcFields(table) def path = dir.getPath() def packageName = path.substring(path.lastIndexOf("java") + 5, path.length()).replaceAll("\\", ".") new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields, packageName) } } def generate(out, className, fields, packageName) { out.println "package $packageName;" out.println "" out.println "import lombok.Data;" out.println "" out.println "@Data" out.println "public class $className {" out.println "" fields.each() { if (it.annos != "") out.println " ${it.annos}" out.println " private ${it.type} ${it.name};" } 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 += [[ name : javaName(col.getName(), false), type : typeStr, 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] }