使用IntelliJ IDEA连接数据库,快速创建实体类对象
1.IntelliJ IDEA连接MySQL数据库
IntelliJ IDEA功能很强大,以前不知道有这样的提升工作效率的方法,虽然有的工具确实可以直接生成实体类,mapper文件,还有dao接口,但是个人觉得涉及到复杂业务还是只生成实体类比较好,后面部分就自己搞定就可以了。
打开项目:
1、点击右侧的Datesource图标,要是没有该图标,请去自行百度
2、点击 + 号
3、选择 datasource
4、选择 mysql
1、填写一个连接名,随便填什么都行
2、填写数据库连接的 IP地址,比如本地数据库可以填写:localhost或者127.0.0.1
3、填写数据库开放的端口号,一般没设置的话默认都是3306
4、选择user&password
5、填写数据库的用户名
6、填写数据库密码
7、填写你需要连接的数据库名
8、这个就是数据库url
9、这里会有一个驱动需要点击下载,图中是已经下载好了
10、ok
其它的操作就和Navicat Premium或者SQL yog的操作差不多了,这里不过多赘述。
2.使用内置方法创建实体类对象
1.首先选择表
2.选择操作
3.选择要生成的位置
3.使用脚本自动创建生成实体类对象,自动生成get,set,toString方法以及无参有参构造器
跟上面方法一样
这里只说如何添加脚本,步骤:
然后创建Generate SimpleBeans.groovy的文件将下面代码复制进去
package com.alibaba.mybatis.entity 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|int/) : "Integer", (~/(?i)bigint/) : "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 "" Set types = new HashSet() fields.each() { types.add(it.type) } if (types.contains("Date")) { out.println "import java.util.Date;" } // 生成开头文档 out.println "" out.println "/**\n" + " * @author xiaozhi\n" + //1. 修改idea为自己名字 " * @create " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \n" + " * @description \n" + " */" out.println "" out.println '@SuppressWarnings("all")' // 去除右边黄色警告,清爽编码环境 out.println "public class $className {" fields.each() { out.println "" // 输出数据库的字段注释 if (isNotEmpty(it.commoent)) { out.println "\t/**" out.println "\t * ${it.commoent.toString()}" out.println "\t */" } // 输出成员变量 out.println "\tprivate ${it.type} ${it.name};" } //生成无参构造函数 out.println "" out.print "\tpublic " out.print className out.print "() {" out.println "}" //生成全参构造函数 out.println "" out.print "\tpublic " out.print className out.print "(" out.print getAllArgs(fields) out.print ") {" out.println "" fields.each() { out.println "\t\tthis.${it.name} = ${it.name};" } out.println "\t}" // 输出toString方法 out.println "" out.println "\t@Override" out.println "\tpublic String toString() {" out.println "\t\treturn \"" + className + "{\" +" out.println getToString(fields) out.println "\t\t\t\t'}';" out.println "\t}" // 输出get/set方法 fields.each() { out.println "" out.println "\tpublic ${it.type} get${it.name.capitalize()}() {" out.println "\t\treturn this.${it.name};" out.println "\t}" out.println "" out.println "\tpublic void set${it.name.capitalize()}(${it.type} ${it.name}) {" out.println "\t\tthis.${it.name} = ${it.name};" out.println "\t}" } out.println "" out.println "}" } def getToString(fields) { StringBuilder str = new StringBuilder() fields.each() { str = str.append("\t\t\t\t\", ${it.name}='\" + ${it.name} + '\\'' +\n") } def s = str.toString().replaceFirst(', ', "") return s.toString().replaceAll('\\n$', "") } def getAllArgs(fields) { StringBuilder AllArgs = new StringBuilder() fields.each() { AllArgs = AllArgs.append("${it.type} ${it.name}, ") } return AllArgs.toString().replaceAll(', $', "") } 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) { str = str.toString() str = str.replaceFirst('t_', "") 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('') } }