IDEA -- 自动生成POJO

1. maven依赖

springboot2、spring-data-jpa、lombok

使用 spring-data-jpa的时候,我们往往不需要生成mapper相关的文件,只需要自动生成POJO类,提高开发效率,这里总结了下自己使用IDEA实现自动生成POJO的方式

2. 步骤

2.1. 在IDEA中连接数据库



2.2. 选择数据库表


2.3. 修改groovy配置文件


参照上面的步骤对配置文件进行个性化修改:

1. 注意修改包名称packageName
2. 添加需要的注解

import com.intellij.database.model.DasTableimport com.intellij.database.model.ObjectKindimport com.intellij.database.util.Caseimport com.intellij.database.util.DasUtilimport java.text.DateFormatimport java.text.SimpleDateFormat/** Available context bindings:* SELECTION Iterable<DasObject>* PROJECT project* FILES files helper*/packageName = "fastcloud.management.pojo;" //这里要换成自己项目 实体的包路径typeMapping = [(~/(?i)int/) : "Integer", //数据库类型和Jave类型映射关系(~/(?i)float|double|decimal|real/): "Double",(~/(?i)bool|boolean/) : "Boolean",(~/(?i)datetime|timestamp/) : "java.util.Date",(~/(?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)new File(dir, className + ".java").withPrintWriter("utf-8") { out -> generate(out, table, className, fields) }}def generate(out, table, className, fields) {def tableName = table.getName()out.println "package $packageName"out.println ""out.println "import lombok.*;"out.println "import org.hibernate.annotations.DynamicInsert;"out.println "import org.hibernate.annotations.DynamicUpdate;"out.println ""out.println "import javax.persistence.*;"out.println ""out.println "/**"out.println " * @author wcy-auto"out.println " **/"out.println "@NoArgsConstructor"out.println "@AllArgsConstructor"out.println "@Getter"out.println "@Builder"out.println "@ToString"out.println "@DynamicUpdate"out.println "@DynamicInsert"out.println "@Entity"out.println "@Table(name = \"$tableName\")"out.println "public class $className extends BaseEntity {"out.println ""// id、createDate、updateDate这些字段我使用了一个BaseEntity,所有的pojo继承此基类,所以不需要创建数据库中的这三个字段,需要的可以自行调整/*if ((tableName + "_id").equalsIgnoreCase(fields[0].colum) || "id".equalsIgnoreCase(fields[0].colum)) {out.println " @Id"out.println " @GeneratedValue(strategy=GenerationType.IDENTITY)"}*/fields.each() {// 这一层if根据需要看是否要保留if (it.name != "id" && it.name != "createTime" && it.name != "updateTime") {if (it.comment != "" && it.comment != null) {out.println " /**"out.println " * ${it.comment}"out.println " **/"}if (it.annos != "") out.println " ${it.annos}"if (it.colum != it.name) {out.println " @Column(name = \"${it.colum}\")"}out.println " private ${it.type} ${it.name};"out.println ""}}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() }.valuefields += [[name : javaName(col.getName(), false),colum : col.getName(),type : typeStr,comment: col.getComment(),annos : ""]]}}def javaName(str, capitalize) {def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }.join("").replaceAll(/[^\p{javaJavaIdentifierPart}]/, "_").replaceAll(/_/, "")capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]}复制代码

2.4. 生成POJO


之后选择要生成的目标文件夹,生成后的POJO如下:

package fastcloud.management.pojo;import lombok.*;import org.hibernate.annotations.DynamicInsert;import org.hibernate.annotations.DynamicUpdate;import javax.persistence.*;/*** @author wcy-auto**/@NoArgsConstructor@AllArgsConstructor@Getter@Builder@ToString@DynamicUpdate@DynamicInsert@Entity@Table(name = "dept")public class Dept extends BaseEntity {/*** 上级部门ID**/@Column(name = "parent_id")private Integer parentId;/*** 部门名称**/private String name;/*** 1 - 正常,0 - 删除**/@Column(name = "del_flag")private Integer delFlag;}复制代码


转载于:https://juejin.im/post/5cdfae96f265da1b6f434430

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值