新建文件
点击任意一张表,右键-【工具】-【脚本化扩展程序】-【转到脚本目录】

在scheme下新建文件myPojos.groovy

文件内容如下
import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import java.io.*
import java.text.SimpleDateFormat
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
packageName = ""
typeMapping = [
(~/(?i)tinyint|smallint|mediumint/) : "Integer",
(~/(?i)int/) : "Long",
(~/(?i)bool|boolean|bit/) : "Boolean",
(~/(?i)float|double|decimal|real/) : "Double",
(~/(?i)datetime|timestamp|date|time/) : "Date",
(~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream",
(~/(?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) {
//想创建的类名 :表名去掉"_" + Bean (teststudentBean)
def className = javaClassName(table.getName(), true)
def fields = calcFields(table)
packageName = getPackageName(dir)
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "UTF-8"))
printWriter.withPrintWriter {out -> generate(out, className, fields,table)}
}
// 获取包所在文件夹路径
def getPackageName(dir) {
return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}
//添加需要的包(或自动导包)
def generate(out, className, fields,table) {
out.println "package $packageName"
out.println ""
out.println "import jakarta.persistence.Column;"
out.println "import jakarta.persistence.Table;"
out.println "import java.io.Serializable;"
out.println "import lombok.*;"
out.println "import org.springframework.format.annotation.DateTimeFormat;"
out.println "import com.fasterxml.jackson.annotation.JsonFormat;"
Set types = new HashSet()
fields.each() {
types.add(it.type)
}
if (types.contains("Date")) {
out.println "import java.util.Date;"
}
if (types.contains("InputStream")) {
out.println "import java.io.InputStream;"
}
out.println ""
//添加生成类的注释内容:常用@author作者及@date时间等,根据需要添加对应的类注释
out.println "/**\n" +
" * @author 作者\n" +
" * @date "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
" */"
out.println ""
//这里使用lombok,添加相应注解
out.println "@Data"
out.println "@NoArgsConstructor"
out.println "@AllArgsConstructor"
out.println "@Entity"
//对应数据库表名
out.println "@Table(name=\""+table.getName() +"\")"
//Serializable
out.println "public class $className implements Serializable {"
out.println ""
out.println genSerialID()
fields.each() {
out.println ""
if (isNotEmpty(it.name)) {
out.println "\t/**"
out.println "\t * ${it.name.toString()} ${it.commoent.toString()}"
out.println "\t */"
}
if (it.annos != "") out.println " ${it.annos}"
//id
if ((className + "_id").equalsIgnoreCase(it.colName) || "id".equalsIgnoreCase(it.colName)) {
out.println "\t@TableId(value = \"id\", type = IdType.AUTO)"
}
//date日期格式字段添加@JsonFormat和@DateTimeFormat注解
if ("Date".equalsIgnoreCase(it.type)) {
out.println '''\t@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")'''
out.println '''\t@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")'''
}
out.println "\t@Column(name=\""+it.colName+"\")"
// Oracle类型处理逻辑
def fieldType = it.type
def columnType = it.columnType?.toString()?.toUpperCase() ?: ""
// 处理Oracle NUMBER类型
if (columnType.startsWith("NUMBER")) {
// 获取精度和小数位(Oracle格式如 NUMBER(10) 或 NUMBER(10,2))
def precision = 0
def scale = 0
def matcher = columnType =~ /NUMBER$(\d+)(?:,(\d+))?$/
if (matcher.find()) {
precision = matcher.group(1)?.toInteger() ?: 0
scale = matcher.group(2)?.toInteger() ?: 0
}
// 根据精度决定映射类型
if (scale > 0) {
fieldType = "BigDecimal" // 有小数位
} else if (precision <= 9) {
fieldType = "Integer" // 小整数
} else if (precision <= 18) {
fieldType = "Long" // 大整数
} else {
fieldType = "BigDecimal" // 超大数字
}
}
out.println "\tprivate ${fieldType} ${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
def comm =[
colName : col.getName(),
name : javaName(col.getName(), false),
type : typeStr,
commoent: col.getComment(),
annos: ""]
fields += [comm]
}
}
// 根据需要处理类名(这里示例类名为teststudentBean)这里去掉_
def javaClassName(str, capitalize) {
def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
.collect { Case.LOWER.apply(it).capitalize() }
.join("")
.replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
}
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]
}
def isNotEmpty(content) {
return content != null && content.toString().trim().length() > 0
}
static String changeStyle(String str, boolean toCamel){
if(!str || str.size() <= 1)
return str
if(toCamel){
String r = str.toLowerCase().split('_').collect{cc -> Case.LOWER.apply(cc).capitalize()}.join('')
return r[0].toLowerCase() + r[1..-1]
}else{
str = str[0].toLowerCase() + str[1..-1]
return str.collect{cc -> ((char)cc).isUpperCase() ? '_' + cc.toLowerCase() : cc}.join('')
}
}
static String genSerialID()
{
return "\tprivate static final long serialVersionUID = "+Math.abs(new Random().nextLong())+"L;"
}