自定义 Generate POJOs.groovy

2年前 (2022) 程序员胖胖胖虎阿
340 0 0
一、Generate文件
  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 import java.sql.Date
  7 
  8 
  9 /*
 10  * Available context bindings:
 11  *   SELECTION   Iterable<DasObject>
 12  *   PROJECT     project
 13  *   FILES       files helper
 14  */
 15 
 16 packageName = "com.sample;"
 17 
 18 typeMapping = [
 19         (~/(?i)tinyint|smallint|mediumint/)      : "Integer",
 20         (~/(?i)int/)                             : "Integer",
 21         (~/(?i)bool|bit/)                        : "Boolean",
 22         (~/(?i)float|double|decimal|real/)       : "Double",
 23         (~/(?i)datetime|timestamp|date|time/)    : "Date",
 24         (~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream",
 25         (~/(?i)number/)                          : "Integer",
 26         (~/(?i)/)                                : "String"
 27 ]
 28 
 29 
 30 FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
 31   SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { generate(it, dir) }
 32 }
 33 
 34 
 35 def generate(table, dir) {
 36   def className = javaClassName(table.getName(), true)
 37   def fields = calcFields(table)
 38   //当是maven项目的时候,需要解开下面的注释
 39 //  packageName = getPackageName(dir)
 40   new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields, table) }
 41 }
 42 
 43 
 44 def generate(out, className, fields, table) {
 45   out.println "package $packageName"
 46   out.println ""
 47   out.println "import javax.persistence.*;"
 48   out.println "import java.io.Serializable;"
 49   out.println "import com.fasterxml.jackson.annotation.JsonIgnore;"
 50   out.println "import io.swagger.annotations.ApiModel;"
 51   out.println "import io.swagger.annotations.ApiModelProperty;"
 52   out.println "import lombok.Data;"
 53   out.println "import org.hibernate.annotations.DynamicInsert;"
 54   out.println "import org.hibernate.annotations.DynamicUpdate;"
 55   out.println "import org.springframework.data.jpa.domain.support.AuditingEntityListener;"
 56 
 57   Set types = new HashSet()
 58 
 59   fields.each() {
 60     types.add(it.type)
 61   }
 62 
 63   if (types.contains("Date")) {
 64     out.println "import java.util.Date;"
 65     out.println "import org.springframework.data.annotation.LastModifiedDate;"
 66     out.println "import org.springframework.data.annotation.CreatedDate;"
 67   }
 68 
 69   if (types.contains("InputStream")) {
 70     out.println "import java.io.InputStream;"
 71   }
 72   out.println ""
 73   out.println "/**\n" +
 74           " * @Description: \n" +
 75           " * @Date: Created in" + new java.util.Date().toString() +"\n"+
 76           " * @Author: Cenobitor\n" +
 77           " * @Modified By:\n" +
 78           " */"
 79   out.println "@Data"
 80   out.println "@Entity"
 81   out.println "@DynamicInsert"
 82   out.println "@DynamicUpdate"
 83   out.println "@EntityListeners(AuditingEntityListener.class)"
 84   out.println "@ApiModel(value=\"\",description=\"\")"
 85   out.println "@Table ( name =\"" + table.getName() + "\" )"
 86   out.println "public class $className  implements Serializable {"
 87   out.println ""
 88   out.println genSerialID()
 89   fields.each() {
 90     out.println ""
 91     // 输出注释
 92     if (isNotEmpty(it.commoent)) {
 93       out.println "\t/**${it.commoent}*/"
 94     }
 95 
 96     if (it.annos != "") out.println "   ${it.annos}"
 97     // 输出成员变量
 98     out.println "\tprivate ${it.type} ${it.name};"
 99   }
100   out.println ""
101   out.println "}"
102 }
103 
104 def calcFields(table) {
105   DasUtil.getColumns(table).reduce([]) { fields, col ->
106     def spec = Case.LOWER.apply(col.getDataType().getSpecification())
107 
108     def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
109     def comm = [
110             colName : col.getName(),
111             name    : changeStyle(javaName(col.getName(), false), true),
112             type    : typeStr,
113             commoent: col.getComment(),
114             annos   : "\t@Column(name = \"" + col.getName() + "\" )"]
115     if ("id".equals(Case.LOWER.apply(col.getName()))){
116       comm.annos = "\t@Id\n"
117       //自增主键需要
118       comm.annos += "\t@GeneratedValue(strategy = GenerationType.IDENTITY)"
119     }
120     if ("create_time".equals(Case.LOWER.apply(col.getName()))){
121       comm.annos += "\n\t@CreatedDate"
122     }
123     if ("update_time".equals(Case.LOWER.apply(col.getName()))){
124       comm.annos += "\n\t@LastModifiedDate"
125     }
126     fields += [comm]
127   }
128 }
129 
130 // 处理类名(这里是因为我的表都是以t_命名的,所以需要处理去掉生成类名时的开头的T,
131 // 如果你不需要那么请查找用到了 javaClassName这个方法的地方修改为 javaName 即可)
132 def javaClassName(str, capitalize) {
133   def s = str.split(/[^\p{Alnum}]/).collect { def s = Case.LOWER.apply(it).capitalize() }.join("")
134   // 去除开头的T  http://developer.51cto.com/art/200906/129168.htm
135   s = s[1..s.size() - 1]
136   capitalize ? s : Case.LOWER.apply(s[0]) + s[1..-1]
137 }
138 
139 def javaName(str, capitalize) {
140   def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }
141           .join("").replaceAll(/[^\p{javaJavaIdentifierPart}]/, "_")
142   capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
143 }
144 
145 def isNotEmpty(content) {
146   return content != null && content.toString().trim().length() > 0
147 }
148 
149 static String changeStyle(String str, boolean toCamel) {
150   if (!str || str.size() <= 1)
151     return str
152 
153   if (toCamel) {
154     String r = str.toLowerCase().split('_').collect { cc -> Case.LOWER.apply(cc).capitalize() }.join('')
155     return r[0].toLowerCase() + r[1..-1]
156   } else {
157     str = str[0].toLowerCase() + str[1..-1]
158     return str.collect { cc -> ((char) cc).isUpperCase() ? '_' + cc.toLowerCase() : cc }.join('')
159   }
160 }
161 
162 static String genSerialID() {
163   return "\tprivate static final long serialVersionUID =  " + Math.abs(new Random().nextLong()) + "L;";
164 }
二、自动生成的实体类
 1 package com.sample;
 2 
 3 import javax.persistence.*;
 4 import java.io.Serializable;
 5 import com.fasterxml.jackson.annotation.JsonIgnore;
 6 import io.swagger.annotations.ApiModel;
 7 import io.swagger.annotations.ApiModelProperty;
 8 import lombok.Data;
 9 import org.hibernate.annotations.DynamicInsert;
10 import org.hibernate.annotations.DynamicUpdate;
11 import org.springframework.data.jpa.domain.support.AuditingEntityListener;
12 import java.util.Date;
13 import org.springframework.data.annotation.LastModifiedDate;
14 import org.springframework.data.annotation.CreatedDate;
15 
16 /**
17  * @Description: 
18  * @Date: Created inWed Nov 06 17:08:23 CST 2019
19  * @Author: Cenobitor
20  * @Modified By:
21  */
22 @Data
23 @Entity
24 @DynamicInsert
25 @DynamicUpdate
26 @EntityListeners(AuditingEntityListener.class)
27 @ApiModel(value="",description="")
28 @Table ( name ="t_staff_role" )
29 public class StaffRole  implements Serializable {
30 
31     private static final long serialVersionUID =  2663305203216589678L;
32 
33 
34     /**自增ID*/
35        @Id
36     @GeneratedValue(strategy = GenerationType.IDENTITY)
37     private Integer id;
38 
39     /**角色名*/
40        @Column(name = "role_name" )
41     private String roleName;
42 
43     /**备注*/
44        @Column(name = "remark" )
45     private String remark;
46 
47     /**创建人*/
48        @Column(name = "create_user" )
49     private String createUser;
50 
51     /**创建时间*/
52        @Column(name = "create_time" )
53     @CreatedDate
54     private Date createTime;
55 
56     /**修改人*/
57        @Column(name = "update_user" )
58     private String updateUser;
59 
60     /**更新时间*/
61        @Column(name = "update_time" )
62     @LastModifiedDate
63     private Date updateTime;
64 
65     /**是否删除   0否 1 是*/
66        @Column(name = "is_deleted" )
67     private String isDeleted;
68 
69 }

 

版权声明:程序员胖胖胖虎阿 发表于 2022年9月2日 上午8:16。
转载请注明:自定义 Generate POJOs.groovy | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...