真会玩!竟然可以这样用IDEA通过数据库生成lombok版的POJO...
前言
最近写需求时需要新建许多新表,设计完表结构还要一一写成对应的 POJO,很麻烦,就 Google 了一下。网上相关资料不多,借鉴了一篇博客,并在其基础上进行了完善。
前置步骤
使用 IDEA 自带的插件 Database 连接数据库
在数据库的表上右键 Scripted Extensions -> Go to Scripts Directory
在打开的目录下放入脚本文件
源码
脚本用的 Groovy 语言,语法类似 Java,并能调用 Java 类库,自己修改也很方便。唯一的麻烦是执行入口在 Intellij 内部,想 debug 很麻烦。
PO 的路径一般都是统一的,如果要在新的模块中使用需要改一下路径。另外类注释需要替换成自己的。
还有一点需要注意的是枚举类型,脚本中将 tinyint 统一映射成了 Boolean 类型,如果要映射成自定义枚举类型,需要在实体类中自行修改。
用于生成带 Lombok 注释的实体类的脚本
Generate Lombok POJOs.groovy:
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtilimport java.time.LocalDate/** Available context bindings:* SELECTION Iterable<DasObject>* PROJECT project* FILES files helper*/// 此处指定包路径,路径需要自行维护;
packageName = "com.xxx.xxx.entity;"
// 此处指定对应的类型映射,可按需修改,目前tinyint如果要映射到自定义枚举类型,只能手动修改
typeMapping = [(~/(?i)bigint/) : "Long",(~/(?i)int/) : "Integer",(~/(?i)tinyint/) : "Boolean",(~/(?i)float|double|decimal|real/): "BigDecimal",(~/(?i)time|datetime|timestamp/) : "LocalDateTime",(~/(?i)date/) : "LocalDate",(~/(?i)/) : "String"
]// 上面用到类和它的导入路径的之间的映射
importMap = ["BigDecimal" : "java.math.BigDecimal","LocalDate" : "java.time.LocalDate","LocalDateTime" : "java.time.LocalDateTime",
]// 导入路径列表,下面引用的时候会去重,也可以直接声明成一个 HashSet
importList = []// 弹出选择文件的对话框
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}def generate(table, dir) {def className = javaName(table.getName(), true) + "PO"def fields = calcFields(table)new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "utf-8")).withPrintWriter { out -> generate(out, className, fields, table) }
}// 从这里开始,拼实体类的具体逻辑代码
def generate(out, className, fields, table) {out.println "package $packageName"out.println ""out.println ""// 引入所需的包out.println "import lombok.Data;"out.println "import javax.persistence.Id;"out.println "import javax.persistence.Table;"out.println "import javax.persistence.GeneratedValue;"// 去重后导入列表importList.unique().each() { pkg ->out.println "import " + pkg + ";"}out.println ""// 添加类注释out.println "/**"// 如果添加了表注释,会加到类注释上if (isNotEmpty(table.getComment())) {out.println " * " + table.getComment()}out.println " *"out.println " * @author xxx"out.println " * @date " + LocalDate.now()out.println " */"// 添加类注解out.println "@Data"out.println "@Table(name = \"${table.getName()}\")"out.println "public class $className {"out.println ""boolean isId = true// 遍历字段,按下面的规则生成fields.each() {// 输出注释if (isNotEmpty(it.comment)) {out.println "\t/**"out.println "\t * ${it.comment}"out.println "\t */"}// 这边默认第一个字段为主键,实际情况大多数如此,遇到特殊情况可能需要手动修改if (isId) {out.println "\t@Id"out.println "\t@GeneratedValue(generator = \"JDBC\")"isId = false}out.println "\tprivate ${it.type} ${it.name};"out.println ""}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() }.valueif (importMap.containsKey(typeStr)) {importList.add(importMap.get(typeStr))}fields += [[name : javaName(col.getName(), false),type : typeStr,comment: col.getComment()]]}
}def isNotEmpty(content) {return content != null && content.toString().trim().length() > 0
}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]
}
用于生成带 Lombok 注释并继承基类的实体类的脚本
Generate Lombok POJOs extend BaseEntity.groovy:
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtilimport java.time.LocalDate/** Available context bindings:* SELECTION Iterable<DasObject>* PROJECT project* FILES files helper*/// 此处指定包路径,路径需要自行维护;
packageName = "com.xxx.xxx.entity;"
// 此处指定对应的类型映射,可按需修改,目前tinyint如果要映射到自定义枚举类型,只能手动修改
typeMapping = [(~/(?i)bigint/) : "Long",(~/(?i)int/) : "Integer",(~/(?i)tinyint/) : "Boolean",(~/(?i)float|double|decimal|real/): "BigDecimal",(~/(?i)time|datetime|timestamp/) : "LocalDateTime",(~/(?i)date/) : "LocalDate",(~/(?i)/) : "String"
]// 上面用到类和它的导入路径的之间的映射
importMap = ["BigDecimal" : "java.math.BigDecimal","LocalDate" : "java.time.LocalDate","LocalDateTime" : "java.time.LocalDateTime",
]// 导入路径列表,下面引用的时候会去重,也可以直接声明成一个 HashSet
importList = []// 基类中已经有的属性,就无需在新生成的类中声明了
userTimeList = ["create_user_id","update_user_id","create_time","update_time"
]// 弹出选择文件的对话框
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}def generate(table, dir) {def className = javaName(table.getName(), true) + "PO"def writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "utf-8"))def fields = calcFields(table)writer.withPrintWriter { out -> generate(out, className, fields, table) }
}// 从这里开始,拼实体类的具体逻辑代码
def generate(out, className, fields, table) {out.println "package $packageName"out.println ""out.println ""// 引入所需的包out.println "import com.xxx.xxx.entity.BaseEntity;"out.println "import lombok.Data;"out.println "import lombok.EqualsAndHashCode;"out.println "import java.io.Serializable;"out.println "import javax.persistence.Id;"out.println "import javax.persistence.Table;"out.println "import javax.persistence.GeneratedValue;"// 去重后导入列表importList.unique().each() { pkg ->out.println "import " + pkg + ";"}out.println ""// 添加类注释out.println "/**"// 如果添加了表注释,会加到类注释上if (isNotEmpty(table.getComment())) {out.println " * " + table.getComment()}out.println " *"out.println " * @author xxx"out.println " * @date " + LocalDate.now()out.println " */"// 添加类注解out.println "@Data"out.println "@EqualsAndHashCode(callSuper = false)"out.println "@Table(name = \"${table.getName()}\")"out.println "public class $className extends BaseEntity implements Serializable {"out.println ""boolean isId = true// 遍历字段,按下面的规则生成fields.each() {// 输出注释if (isNotEmpty(it.comment)) {out.println "\t/**"out.println "\t * ${it.comment}"out.println "\t */"}// 这边默认第一个字段为主键,实际情况大多数如此,遇到特殊情况可能需要手动修改if (isId) {out.println "\t@Id"out.println "\t@GeneratedValue(generator = \"JDBC\")"isId = false}out.println "\tprivate ${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() }.value// 如果是BaseTimeUserIdPO中已有的字段,则不再添加if (!userTimeList.contains(col.getName())) {// 如果是需要导入的类型,则往list里面添加if (importMap.containsKey(typeStr)) {importList.add(importMap.get(typeStr))}fields += [[name : javaName(col.getName(), false),type : typeStr,dbType : col.getDataType(),comment: col.getComment()]]} else {fields += []}}
}def isNotEmpty(content) {return content != null && content.toString().trim().length() > 0
}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]
}
使用方法
在 Database 中选中需要生成实体类的表(可以多选),右键 Scripted Extensions 选择需要执行的脚本,在弹出的对话框中选择生成文件的目标目录,OK。
参考资料
[1] idea通过数据库生成java实体类(lombok版)
如果觉得写的不错,请记得转发或者在看,这是对我最大的认可和鼓励!
作者:sisibeloved
来源:https://juejin.im/post/5ca5d01f5188257e1d45707a
真会玩!竟然可以这样用IDEA通过数据库生成lombok版的POJO...相关推荐
- idea persistence生成_真厉害!竟然可以这样用IDEA通过数据库生成lombok版的POJO...
前言 最近写需求时需要新建许多新表,设计完表结构还要一一写成对应的 POJO,很麻烦,就 Google 了一下.网上相关资料不多,借鉴了一篇博客,并在其基础上进行了完善. 前置步骤 使用 IDEA 自 ...
- 日本人真会玩!3天众筹60万元来造“机器猫”,会说话摇尾巴的那种
杨净 发自 凹非寺 量子位 报道 | 公众号 QbitAI 日本人真会玩! 这只毛线猫竟然要2000多块?! 虽然必须得承认,这确实不是一只简单的毛线猫. 而是会摇尾巴.眨眼睛来吸引你的注意,在线求撸 ...
- 自行车 forum.php,[你们城里人真会玩]关于大行折叠自行车18速..
[你们城里人真会玩]关于大行折叠自行车18速.. [attachment=751828] 新手路过..连辆自行车都没有的真新手..最近琢磨买辆折叠自行车,在论坛转了2天都晕了..083家族好复杂,今天 ...
- 中文真伟大!竟然有只能看,不能读的文章
1.赵元任<施氏食狮史> 石室诗士施氏,嗜狮,誓食十狮.施氏时时适市视狮.十时,适十狮适市.是时,适施氏适市.氏视是十狮,恃矢势,使是十狮逝世.氏拾是十狮尸,适石室.石室湿,氏使侍拭石室. ...
- 马云唱京剧《空城计》,柳传志说相声:“商界春晚”大佬们真会玩(附视频)...
当马云.柳传志.曹国伟等人聚在一起,会发生什么? 在互联网大会上共论未来十年的发展趋势?还是在镜头前激烈探讨行业变化? 然而这次都不是. 他们聚在一起,是为了上"春晚"表演节目-- ...
- 【真会玩】- SpringCloud Netflix 实战笔记 -【Eureka】
文章目录 友情提醒 前置环境搭建 Eureka 概念初识 服务注册 服务发现 续租 拉取注册表 Cancel 同步时间延时 通讯机制 Eureka服务端搭建 Eureka客户端 Provider搭建 ...
- 抖音康辉机器人_抖音惊现新闻联播主持人康辉,翻白眼卖萌放飞自我,网友:真会玩...
随着网络信息技术的发展,出现了越来越多的社交媒体平台,大家最喜欢的应该就是各种短视频和直播软件了,特别是现在的一些短视频发展的真是非常迅速,其中最受欢迎的应该就是抖音了,很短的时间内,就发展了很多的用 ...
- python纯函数_理想国真恵玩Python从入门到精通第006天_纯函数写游戏管理系统
原标题:理想国真恵玩Python从入门到精通第006天_纯函数写游戏管理系统 前面已经带大家学习了函数,高级数据类型,比如说字典,今天带大家用函数加字典做一个游戏管理系统,希望大家喜欢.废话不多说,直 ...
- 计算机打印机软驱,用软驱、硬盘、打印机组合成乐器?外国人真会玩!
原标题:用软驱.硬盘.打印机组合成乐器?外国人真会玩! 讲了这么多期中国的民间乐器,今天咱们也换换口味,看看外国的民间大神们带来的"硬核"乐器 近几年短视频流行起来后,大家对那些用 ...
- ROS系统MoveIt玩转双臂机器人系列(二)--生成MoveIt配置包
ROS系统MoveIt玩转双臂机器人系列(二)--生成MoveIt配置包 注:本篇博文全部源码下载地址为:Git Repo. 1. 下载到本地后解压到当前文件夹然后运行:catkin_make 编译. ...
最新文章
- datetime类型需要指定长度吗_你真的用对数据库了吗?
- 44 Wild card Matching
- 数据恢复专业基础之python解释NTFS runlist的代码
- Android开发--环境的配置
- echarty轴自定义显示不全_表格打印不全怎么办?这招超简单!
- uva 10692——Huge Mods
- 计算机专业英语基础篇
- 朱邦芬院士:我所熟悉的几位中国物理学大师的为人之本
- 模板题——图论相关(2)
- OAuth 2 开发人员指南(Spring security oauth2)
- springboot的if else过多解决方案
- 基于PROFINET技术的STEP7组态
- 自学DevExpress为Form表格换肤
- 嵌入式Linux学习笔记
- 一个计算机爱好者的不完整回忆(三十一)我的拼音输入法
- nx零件库插件_3DSource企业自定义零件库插件
- baidu 地图 3d版 自定义地图样式
- HTML5 CSS3 专题 :诱人的实例 3D旋转木马效果相冊
- Spring Boot 实践折腾记(13):使用WebFlux构建响应式「推送API 」
- Python学习笔记Day01--Day06
热门文章
- Illustrator中文版教程,如何在 Illustrator 中使用自由变换工具?
- inDesign教程,如何创建交互式简历?
- 如何打开 Mac 的摄像头?
- iOS开发Cocoapods执行命令pod setup,执行失败解决RPC failed; curl 56 LibreSSL SSL_read: SSL_ERROR_SYSCALL, errno 54
- QuarkXPress 2022 for mac(排版设计软件)
- MATLAB R2021b for Mac(可视化数学分析软件)
- EditRocket for Mac(源代码编辑器)v4.5.10
- MAC硬盘空间减少的隐藏杀手,VM到底是什么?
- Springboot中如何在Utils类中使用@Autowired注入bean
- RabbitMq异常处理