Generating JPA Entity Classes in IntelliJ IDEA Using Groovy Scripts
The article provides a step‑by‑step tutorial on configuring database connections in IntelliJ IDEA, using its built‑in tools to generate simple POJOs or JPA‑annotated entities, and creating a custom Groovy script to produce fully annotated Java entity classes directly from a database schema.
This article explains how to generate JPA‑annotated entity classes directly from a database schema using IntelliJ IDEA.
First it shows how to configure a database connection in the Ultimate edition of IDEA, including driver download and connection parameters.
Then it describes the two built‑in generation methods: (1) generating simple POJOs without annotations via the “Generate POJOs.groovy” script, and (2) generating JPA‑annotated entities using the Persistence tool after adding the JPA module.
Finally it provides a step‑by‑step guide to create a custom Groovy script that produces fully annotated entity classes, covering script placement, package handling, field mapping, annotation insertion, and optional enhancements such as hashCode/equals generation. The complete script source is included.
Running the script from the Database tool window creates Java files with @Entity, @Table, @Id, @Column annotations and standard getters, setters, toString and serialVersionUID.
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.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|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) {
def className = javaName(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 javax.persistence.Column;"
out.println "import javax.persistence.Entity;"
out.println "import javax.persistence.Table;"
out.println "import javax.persistence.Id;"
out.println "import javax.persistence.GeneratedValue;"
out.println "import java.io.Serializable;"
if (fields.any { it.type == "Date" }) out.println "import java.util.Date;"
if (fields.any { it.type == "InputStream" }) out.println "import java.io.InputStream;"
out.println ""
out.println "/**
* @Description
* @Author idea
* @Date " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "
*/"
out.println ""
out.println "@Entity"
out.println "@Table(name=\"" + table.getName() + "\", schema=\"\")"
out.println "public class $className implements Serializable {"
out.println ""
out.println genSerialID()
fields.each {
out.println ""
if (isNotEmpty(it.commoent)) {
out.println "\t/**"
out.println "\t * ${it.commoent.toString()}"
out.println "\t */"
}
if (it.annos.contains("[@Id]")) out.println "\t@Id"
if (it.annos != "") out.println "\t${it.annos.replace("[@Id]", "")}"
out.println "\tprivate ${it.type} ${it.name};"
}
fields.each {
out.println ""
out.println "\tpublic ${it.type} get${it.name.capitalize()}() {"
out.println "\t return this.${it.name};"
out.println "\t}"
out.println ""
out.println "\tpublic void set${it.name.capitalize()}(${it.type} ${it.name}) {"
out.println "\t this.${it.name} = ${it.name};"
out.println "\t}"
}
out.println ""
out.println "\t@Override"
out.println "\tpublic String toString() {"
out.println "\t return \"TpApiConfig{\" +"
fields.each { out.println "\t \"${it.name}='\" + ${it.name} + '\'' + \"\" +" }
out.println "\t '}';"
out.println "\t}"
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 : "\t@Column(name = \"" + col.getName() + "\")"
]
if ("id".equals(Case.LOWER.apply(col.getName()))) comm.annos += ["@Id"]
fields += [comm]
}
}
def javaName(str, capitalize) {
def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
.collect { Case.LOWER.apply(it).capitalize() }
.join("")
.replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
return 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 genSerialID() {
return "\tprivate static final long serialVersionUID = " + Math.abs(new Random().nextLong()) + "L;"
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
