IDEA如何从数据库表生成带字段注释的Model,解决乱码问题,还有自动生成controller问题
写在前面
刚开始也从网上找了很多,但都不好用,注释,注解什么的都不太好,后来参照几个对应修改的
关于IDEA连接数据库的问题,参考一下,这个,这里主要是对之前的Groovy文件优化,解决乱码,调整出自己需要的生成脚本
一、生成Model
//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 com.google.common.base.CaseFormat
import com.intellij.database.model.DasObject
import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
packageName = "com.sample;"
typeMapping = [
(~/(?i)bigint/) : "Long",
(~/(?i)int/) : "Integer",
(~/(?i)float|double|decimal|real/): "Double",
(~/(?i)datetime|timestamp/) : "java.time.LocalDateTime",
(~/(?i)date/) : "java.sql.Date",
(~/(?i)time/) : "java.sql.Time",
(~/(?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)
new File(dir, className.replace('_', '') + ".java").withPrintWriter('UTF-8') { out -> generate(out, className, fields) }
}
def generate(out, className, fields) {
out.println "package $packageName"
out.println ""
out.println ""
out.println "import lombok.Getter;"
out.println "import lombok.Setter;"
out.println "import javax.persistence.*;"
// out.println "import java.sql.Timestamp;"
out.println ""
out.println "@Entity"
out.println "@Table(name = \"${className.toLowerCase()}\")"
out.println "@Setter @Getter"
out.println "public class ${className.replace('_', '')} implements Serializable {"
out.println ""
out.println genSerialId()
out.println ""
fields.each() {
// 字段注释
// if (it.commoent != "" && it.commoent!="null")out.println " // ${it.commoent}"
if (it.annos != "") out.println " ${it.annos}"
if (it.name == 'id') {
out.println " @Id"
out.println " @GeneratedValue(strategy = GenerationType.AUTO)"
}
if (it.name.contains('_'))
out.println " @Column(name = \"${it.name.toLowerCase()}\")"
out.println " private ${it.type} ${it.name.replace('_', '')};"
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
fields += [[
name : javaName(col.getName(), false),
type : typeStr,
annos: ""]]
}
}
def calcFields(DasObject table) {
DasUtil.getColumns(table).reduce([]) { fields, col ->
def spec = Case.LOWER.apply(col.dataType.specification)
def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
fields += [[
name : javaName(col.name, false),
type : typeStr,
annos: """
/**
* $col.comment
*/"""]]
}
}
def javaName(str, capitalize) {
def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }
.join("").replaceAll(/[^\p{javaJavaIdentifierPart}]/, "_")
capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
static String genSerialId(){
return "\tprivate static final long serialVersionUID = " + Math.abs(new Random().nextLong()) + "L";
}
二、生成Controller
import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
packageName = "com.sample;"
typeMapping = [
(~/(?i)int/) : "long",
(~/(?i)float|double|decimal|real/): "double",
(~/(?i)datetime|timestamp/) : "java.sql.Timestamp",
(~/(?i)date/) : "java.sql.Date",
(~/(?i)time/) : "java.sql.Time",
(~/(?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)
new File(dir, className + "Controller.java").withPrintWriter { out -> generate(out, className, fields, table.getName()) }
}
def generate(out, className, fields, tableName) {
def camelClassName = Case.LOWER.apply(className.substring(0,1)) + className.substring(1)
out.println "package $packageName"
out.println ""
out.println "import org.springframework.http.ResponseEntity;"
out.println "import org.springframework.web.bind.annotation.*;"
out.println ""
out.println "@RestController"
out.println "@RequestMapping(\"/${Case.LOWER.apply(className)}\")"
out.println "public class ${underscoreToCamelCase(className)}Controller extends BaseController {"
out.println ""
out.println " private ${underscoreToCamelCase(className)}Service ${camelClassName}Service;"
out.println ""
out.println " public ${underscoreToCamelCase(className)}Controller(${underscoreToCamelCase(className)}Service service) {"
out.println " this.${camelClassName}Service = service;"
out.println " }"
out.println ""
out.println " @RequestMapping(method = RequestMethod.GET)"
out.println " public ResponseEntity<Iterable<${underscoreToCamelCase(className)}Model>> findAll() {"
out.println " Iterable<${underscoreToCamelCase(className)}Model> all${className} = this.${camelClassName}Service.findall(0, 100);"
out.println " return Ok(all${className});"
out.println " }"
out.println ""
out.println " @RequestMapping(value = \"/{page}/{pageSize}\", method = RequestMethod.GET)"
out.println " public ResponseEntity<Iterable<${underscoreToCamelCase(className)}Model>> findAll(@PathVariable(\"page\") final Integer page, @PathVariable(\"pageSize\") final Integer pageSize) {"
out.println " Iterable<${underscoreToCamelCase(className)}Model> all${className} = this.${camelClassName}Service.findall(page, pageSize);"
out.println " return Ok(all${className});"
out.println " }"
out.println ""
out.println " @RequestMapping(value = \"/{id}\", method = RequestMethod.GET)"
out.println " public ResponseEntity<${underscoreToCamelCase(className)}Model> get(@PathVariable(\"id\") final Long id) {"
out.println " ${underscoreToCamelCase(className)}Model entry = this.${camelClassName}Service.find(id);"
out.println " return Ok(entry);"
out.println " }"
out.println ""
out.println " @RequestMapping(method = RequestMethod.POST)"
out.println " public ResponseEntity<${underscoreToCamelCase(className)}Model> create(@RequestBody final ${underscoreToCamelCase(className)}Model creating) {"
out.println " ${underscoreToCamelCase(className)}Model created = this.${camelClassName}Service.create(creating);"
out.println " return Ok(created);"
out.println " }"
out.println ""
out.println " @RequestMapping(method = RequestMethod.PUT)"
out.println " public ResponseEntity<${underscoreToCamelCase(className)}Model> update(@RequestBody final ${underscoreToCamelCase(className)}Model updating) {"
out.println " ${underscoreToCamelCase(className)}Model updated = this.${camelClassName}Service.update(updating);"
out.println " return Ok(updated);"
out.println " }"
out.println ""
out.println " @RequestMapping(value = \"/{id}\", method = RequestMethod.DELETE)"
out.println " public ResponseEntity delete(@PathVariable(\"id\") final Long id) {"
out.println " this.${camelClassName}Service.delete(id);"
out.println " return Ok();"
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
fields += [[
name : javaName(col.getName(), false),
type : typeStr,
annos: "",
colName: col.getName(),
primary: DasUtil.isPrimary(col)
]]
}
}
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]
}
String underscoreToCamelCase(String underscore){
if(!underscore || underscore.isAllWhitespace()){
return ''
}
return underscore.replaceAll(/_\w/){ it[1].toUpperCase() }
}