当前位置: 首页 > news >正文

IDEA导出数据库对应的实体配置

  笔者时常因为各种原因重装IDEA软件,导致有些配置找不到,或者忘记如何进行配置的。本次是自我配置(结合AI提示)编写了一个比较完整的 .groovy 文件。也可能因为使用的规则不同,请结合自己的需求进行修改.。

import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import com.intellij.database.model.ObjectKind
import java.time.LocalDate
import java.time.format.DateTimeFormatter/** Available context bindings:*   SELECTION   Iterable<DasObject>*   PROJECT     project*   FILES       files helper*/packageName = "com.wjin.domain;"
typeMapping = [// 数值类型(~/(?i)tinyint/)            : "Byte",(~/(?i)smallint/)           : "Short",(~/(?i)int|integer/)        : "Integer",(~/(?i)bigint/)             : "Long",(~/(?i)decimal|numeric/)    : "BigDecimal",(~/(?i)real|float/)         : "Float",(~/(?i)double/)             : "Double",// 字符串类型(~/(?i)char|varchar|text|longtext|mediumtext|tinytext/) : "String",// 日期时间类型(~/(?i)date/)               : "Date",(~/(?i)time/)               : "Date",(~/(?i)datetime|timestamp/) : "Date",// 其他特殊类型(~/(?i)bit/)                : "Boolean",(~/(?i)bool|boolean/)       : "Boolean",(~/(?i)blob|binary|varbinary|longblob|mediumblob|tinyblob/) : "byte[]",(~/(?i)year/)               : "Integer",// 默认类型(~/(?i).*/)                 : "String"
]FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->def tables = SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }def totalTables = tables.size()def processedCount = 0tables.each { table ->try {def className = javaName(table.getName(), true)def fields = calcFields(table)def file = new File(dir, className + ".java")// 检查文件是否已存在if (file.exists()) {// 这里可以根据需要添加用户确认逻辑println "Warning: File ${file.name} already exists and will be overwritten"}// 检查目录写入权限if (!dir.canWrite()) {throw new IOException("Cannot write to directory: ${dir.absolutePath}")}// 使用UTF-8编码写入文件file.withPrintWriter("UTF-8") { out ->generate(out, className, fields, table)}processedCount++println "Generated: ${file.name} (${processedCount}/${totalTables})"} catch (Exception e) {println "Error processing table ${table.getName()}: ${e.message}"// 可以选择继续处理其他表或停止执行}}
}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, className, fields, table) }
}def generate(out, className, fields, table) {out.println "package $packageName"out.println ""out.println ""out.println "/**"def tableComment = table.getComment() ?: className// 确保注释正确编码out.println " * @Desc: ${tableComment.toString()}"out.println " * @Author: w_jin"// 使用更可靠的日期格式化方法def currentDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))out.println " * @Date ${currentDate}"out.println " */"out.println "public class $className {"out.println ""fields.each() {if (it.annos != "") out.println "  ${it.annos}"out.println "    /**"def fieldComment = it.comment ?: it.nameout.println "     * ${fieldComment.toString()}"out.println "     */"out.println "  private ${it.type} ${it.name};"}out.println ""fields.each() {out.println ""out.println "   /**"def fieldComment = it.comment ?: it.nameout.println "    * 获取${fieldComment.toString()}"// 对Date类型使用特殊处理if (it.type == "Date") {out.println "    * @return ${it.name} ${fieldComment.toString()}"out.println "    */"out.println "  public ${it.type} get${it.name.capitalize()}() {"out.println "    return ${it.name} != null ? (Date) ${it.name}.clone() : null;"out.println "  }"} else {out.println "    * @return ${it.name} ${fieldComment.toString()}"out.println "    */"out.println "  public ${it.type} get${it.name.capitalize()}() {"out.println "    return ${it.name};"out.println "  }"}out.println ""out.println "   /**"out.println "    * 设置${fieldComment.toString()}"// 对Date类型使用特殊处理if (it.type == "Date") {out.println "    * @param ${it.name} ${fieldComment.toString()}"out.println "    */"out.println "  public void set${it.name.capitalize()}(${it.type} ${it.name}) {"out.println "    this.${it.name} = ${it.name} != null ? (Date) ${it.name}.clone() : null;"out.println "  }"} else {out.println "    * @param ${it.name} ${fieldComment.toString()}"out.println "    */"out.println "  public void set${it.name.capitalize()}(${it.type} ${it.name}) {"out.println "    this.${it.name} = ${it.name};"out.println "  }"}out.println ""}out.println "}"
}def calcFields(table) {DasUtil.getColumns(table).reduce([]) { fields, col ->def spec = Case.LOWER.apply(col.getDasType().getSpecification())def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.valuefields += [[name : javaName(col.getName(), false),type : typeStr,comment: col.getComment(),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]
}
http://www.vanclimg.com/news/172.html

相关文章:

  • 2025最佳代码托管平台推荐
  • 搜索
  • 服务器docker
  • 一种绕定轴旋转的参照系上的惯性力推导方法
  • 划分点(Vertex)和边(Edge)的属性汇总
  • 基本算法
  • JimuReport 积木报表 v2.1.1 版本发布,免费开源的报表和大屏设计
  • 一期6.文本摘要(md版)
  • 虚拟机之间实现免密登录,SSH密钥认证
  • 新认识了一个既简单又好用的AI修图工具丨PhotoDirector Ultra 2025 v16.6 相片大师
  • LGP4171 [JSTS 2010] 满汉全席 学习笔记
  • 2025年7款效率翻倍项目管理软件工具清单,项目经理生存手册!
  • Java初步了解
  • 微服务学习-01-微服务技术栈导学
  • CVE-2021-25646 Apache Druid 远程代码执行漏洞 (复现)
  • 9N90-ASEMI工业驱动专用9N90
  • 读后感
  • 我的 10 级 Claude Code 速查表让你几分钟内变专家(你现在是第几级?)
  • Docker容器服务端口探测 - Leonardo
  • Docker搭建Hadoop集群
  • 总结与计划 7.28
  • Inventory System Plugin
  • 联邦学习中的持续学习技术
  • CHO细胞抗体表达|重组抗体纯化|高效抗体生产
  • new
  • (阶段二:落地) CMS 模板系统核心数据结构与流程梳理(SceneStack)
  • CAXA3D 实体设计2025最新版本下载安装图文教程,一键快速安装激活
  • 前端开发者的利器:6款最强类EXCEL表格插件对比,轻松实现Excel级交互
  • 软考系统分析师每日学习卡 | [日期:2025-07-28] | [今日主题:操作系统概述]
  • xshell的正则表达式