1、打开窗口 DataBase
2、配置参数
①端口port 默认的可以不写
②Database必须得写 查询到 是哪个数据表
③驱动 没有的话点击自行下载(方便)
④ Test 测试连接成功
3、查看数据库中的数据表
点击 OK 以后 查看DataBase对话框 发现没有数据库中的列表
点击 “0 of 7” 选择dbo
点击外侧即可出现数据库列表
4、查看数据表信息
双击数据表可以在左侧查看数据表的内容
5、生成实体
①创建文件夹存放model
②选中要生成实体的表
③选择实体存放的位置
④ 自动生成实体 方便
6、问题
idea database 生成实体类 数据表中字段是int类型 自动生成的是long类型 ???
查看Generate POJOs.groovy 发现 设置默认int转成long 肯定是有目的的
id主键自增 增到不能再增的时候就得使用long了
Generate POJOs.groovy
import com.intellij.database.model.DasTable
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 }.each { generate(it, dir) }
}
def generate(table, dir) {
def className = javaName(table.getName(), true)
def fields = calcFields(table)
new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields) }
}
def generate(out, className, fields) {
out.println "package $packageName"
out.println ""
out.println ""
out.println "public class $className {"
out.println ""
fields.each() {
if (it.annos != "") out.println " ${it.annos}"
out.println " private ${it.type} ${it.name};"
}
out.println ""
fields.each() {
out.println ""
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) {
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 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]
}