idea generates annotated entity classes automatically
idea generates annotated entity classes automatically
Explain
The idea itself has an operation method to generate entity classes, but it is inconvenient to generate entity classes without annotations. You can use the following methods to generate entity classes with annotations
idea configuration database
Open the database on the far right side of idea, and click in
Choose to add a new database type. We have MySQL as an example and choose mysql
In the pop-up window, fill in the key information of mysql link, address (default localhost), port (default 3306), user name, password, and then click Test connection. If Successful, the link is Successful. Click the lower right corner to confirm
idea add groovy file
At this time, we can directly generate entity classes, and select Generate POJOs.groovy
At this time, the generated entity has no annotation. We can select Go to Scripts Directory
At this time, the system will automatically navigate to the directory of Generate POJOs.groovy. We will create a new GenerateMYPOJOs.groovy in the secondary directory to copy the following contents. Of course, you can also define a set of generation rules or
Find a set of required generation rules to add
import com.intellij.database.model.DasTable import com.intellij.database.model.ObjectKind import com.intellij.database.util.Case import com.intellij.database.util.DasUtil typeMapping = [ (~/(?i)number\(\d\)/) : "int", (~/(?i)number/) : "double", (~/(?i)int/) : "int", (~/(?i)long/) : "long", (~/(?i)float|double|decimal|real/): "double", (~/(?i)timestamp|datetime|date|time/) : "LocalDateTime", (~/(?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) def file = new File(dir,className+".java") def packageName = dir.toString().replaceAll("\\\\", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";" def writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8")) writer.withPrintWriter { out -> generate(out, table, fields, packageName) } } def generate(out, table, fields, packageName) { def tableName = table.getName() def className = javaName(tableName, true) def tableComment = table.getComment() def hasPK = DasUtil.getPrimaryKey(table)!=null def hasDatetime = false fields.each() {hasDatetime=hasDatetime||it.type=="LocalDateTime"} out.println "package $packageName" out.println "" out.println "import javax.persistence.*;" if (hasPK) out.println "import java.time.LocalDateTime;" out.println "import org.hibernate.annotations.GenericGenerator;" out.println "" if (tableComment != "" && tableComment != null){ out.println "/**" out.println " * ${tableComment}" out.println " */" } if (hasPK) out.println "@Entity" out.println "@Table(name = \"${tableName}\")" out.println "public class $className {" out.println "" fields.each() { out.println " //${it.commoent} ${it.spec}" out.println " private ${it.type} ${it.name};" out.println "" } fields.each() { out.println "" if (it.isId) out.println " @Id" if (it.isId) out.println " @GeneratedValue()" if (it.annos != "") out.println " ${it.annos}" out.println " public ${it.type} get${it.name.capitalize()}() {" out.println " return ${it.name};" out.println " }" 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) { def primaryKey = DasUtil.getPrimaryKey(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 colName = col.getName() fields += [[ name : javaName(col.getName(), false), type : typeStr, commoent: col.getComment(), spec:spec, isId : primaryKey != null && DasUtil.containsName(colName, primaryKey.getColumnsRef()), annos : "@Column(name = \"${colName}\")", ]] } } 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] }
Generate annotated entities
At this point, we regenerate, select GenerateMYPOJOs.groovy that we just added, and our class will be annotated
summary
On the whole, this generation method is not very convenient. Using MyBatis Generator or hibernate can automatically generate entity classes, which is also quite convenient. I've seen before that a God wrote a set of program directly to input data source information, and the selection table can automatically generate the required xml,bean,service,dao structure codes. Of course, the most important one is suitable for himself