创建数据库连接,如果侧栏没有database,可以在plugins中看插件是否开启
拓展一下,使用MybatisX插件生产(零代码,比下边这个更灵活)
链接 --》Mybatis-X插件自动生成代码的使用详解(小白专用)
上边都操作完之后是这样
你如果是第一次, 会直接提示你下载,不是我这个switch to latest driver,下载就好了
我这个怎么解决 ↓ ↓ 选择最新的就行
然后 apply 返回上去,再测试连接
连接成功之后,
生成默认实体类,注意生成位置是你源码对应实体类包
看这优秀的包名优秀的类名优秀的数据类型,没得序列化接口,没得equals,没得tostring
救星来了
这个文件,在同目录下复制一,代码如下(对不起小白尽力了,包名多个点麻烦大佬们自己删一下)。
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.io.*
import java.text.SimpleDateFormat
/*
* Available context bindings:
* SELECTION Iterable
* PROJECT project
* FILES files helper
*/
packageName = ""
typeMapping = [
(~/(?i)tinyint|smallint|mediumint/) : "Integer",
(~/(?i)int/) : "Integer",
(~/(?i)bool|bit/) : "Boolean",
(~/(?i)float|double|decimal|real/) : "Double",
(~/(?i)datetime|timestamp|date|time/) : "String",
(~/(?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 = javaClassName(table.getName(), true)
// 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) }
// new File(dir, className + ".java").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) {
def tableName = table.getName()
out.println "package $packageName"
out.println ""
out.println "import java.io.Serializable;"
out.println "import com.baomidou.mybatisplus.annotation.TableName;"
out.println "import com.fasterxml.jackson.annotation.JsonIgnoreProperties;"
out.println "import com.fasterxml.jackson.annotation.JsonInclude;"
out.println "import lombok.NoArgsConstructor;"
out.println "import lombok.EqualsAndHashCode;"
out.println "import lombok.Getter;"
out.println "import lombok.Setter;"
out.println "import lombok.ToString;"
Set types = new HashSet()
fields.each() {
types.add(it.type)
}
if (types.contains("Date")) {
out.println "import java.util.Date;"
}
if (types.contains("InputStream")) {
out.println "import java.io.InputStream;"
}
out.println ""
out.println "/**\n" +
" * @Description \n" +
" * @Author \n" +
" * @Date " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
" */"
out.println "@Getter"
out.println "@Setter"
out.println "@ToString"
out.println "@NoArgsConstructor"
out.println "@EqualsAndHashCode"
out.println "@JsonInclude(JsonInclude.Include.NON_NULL)"
out.println "@JsonIgnoreProperties(value = {\"hibernateLazyInitializer\", \"handler\", \"fieldHandler\"}, ignoreUnknown = true)"
out.println "@TableName(\"" + table.getName() + "\")"
out.println "public class $className implements Serializable {"
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 != "") out.println " ${it.annos.replace("[@Id]", "")}"
if (("id").equalsIgnoreCase(it.name) || (it.name.contains("Id") && !it.type.equals("String"))) {
// 输出成员变量
// out.println "\tprivate Long ${it.name};"
out.println "\tprivate ${it.type} ${it.name};"
} else {
out.println "\tprivate ${it.type} ${it.name};"
}
}
// 输出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}"
// }
// toString方法
// out.println "\t@Override"
// out.println "\tpublic String toString() {"
// out.print "\t\t return "
// out.print "\"$className"
// out.println "{\"+ "
// fields.each() {
// out.println "\t\t\t\", ${it.name}='\" + ${it.name} + '\\'' +"
// }
// out.println "\t\t'}\';"
// out.println "\t}"
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
def comm = [
colName : col.getName(),
name : javaName(col.getName(), false),
type : typeStr,
commoent: col.getComment(),
annos : ""]
fields += [comm]
}
}
// 处理类名(这里是因为我的表都是以t_命名的,所以需要处理去掉生成类名时的开头的tb,
// 如果你不需要那么请查找用到了 javaClassName这个方法的地方修改为 javaName 即可)
def javaClassName(str, capitalize) {
def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
.collect { Case.LOWER.apply(it).capitalize() }
.join("")
.replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
// 去除开头的tb
//如果 t_开头,下边的2改为1
s = s[2..s.size() - 1]
capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
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]
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('')
}
}
static String genSerialID() {
return "\tprivate static final long serialVersionUID = " + Math.abs(new Random().nextLong()) + "L;"
}
--------------------------------------------------------------------------------------------------------------------------------
补充一下发现的异常
解决办法就是在url后边加上?useSSL=false 就可以了
-------------------------------------------------------------------------------------------------------------------------------