idea中导出数据库的表的实体类并带有注释
⼀、连接数据库
打开项⽬:
1、点击右侧的Database图标
2、点击 + 号
3、选择 datasource
4、选择 mysql
5、填写数据库连接的 IP地址,⽐如本地数据库可以填写:localhost或者127.0.0.1
6、填写数据库开放的端⼝号,⼀般没设置的话默认都是3306
7、你需要连接的数据库名
8、写数据库的⽤户名
9、写数据库密码
10、个驱动需要点击下载,图中是已经下载好了
11、⾃⼰的数据库连接url,然后可以点击9所在按钮进⾏测试连接,本地连接失败检查是否开启了mysql服务
连接好了可以看到⾃⼰的数据库和表,选择⼀个表右键,选择scripted Extentions---->Go to scripts Directory ,然后再schema中创建⾃定义格式的⽂件 vy ,如下图。
将下⾯的代码粘贴到新建的 vy ⽂件中:
import com.del.DasTable
import com.del.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import java.io.*
SimpleDateFormat
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
packageName = ""
typeMapping = [
(~/(?i)tinyint|smallint|mediumint/) : "Integer",
(~/(?i)int/) : "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 = Name(), 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) {
String().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}
def generate(out, className, fields,table) {
out.println "package $packageName"
out.println ""
out.println "import javax.persistence.Column;"
out.println "import javax.persistence.Entity;"
out.println "import javax.persistence.Table;"
out.println "import java.io.Serializable;"
out.println "import lombok.Getter;"
out.println "import lombok.Setter;"
out.println "import lombok.ToString;"
Set types = new HashSet()
fields.each() {
types.pe)
}
if (ains("Date")) {
out.println "import java.util.Date;"
}
if (ains("InputStream")) {
out.println "import java.io.InputStream;"
}
out.println ""
out.println "/**\n" +
" * @Description \n" +
" * @Author xiao\n" +
" * @Date "+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \n" +
" */"
out.println ""
// out.println "@Setter"
// out.println "@Getter"
/
/ out.println "@ToString"
out.println "@Entity"
out.println "@Table ( name =\""+Name() +"\" )"
out.println "public class $className implements Serializable {"
out.println ""replaceall()
out.println ""
out.println genSerialID()
fields.each() {
out.println ""
// 输出注释
if (isNotEmpty(itmoent)) {
out.println "\t/**"
out.println "\t * ${String()}"
out.println "\t */"
}
if (it.annos != "") out.println " ${place("[@Id]", "")}"
// 输出成员变量
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}"
}
out.println ""
out.println "}"
}
def calcFields(table) {
def spec = Case.LOWER.DataType().getSpecification())
def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
def comm =[
colName : Name(),
name : Name(), false),
type : typeStr,
commoent: Comment(),
annos: "\t@Column(name = \""+Name()+"\" )"]
if("id".equals(Case.LOWER.Name())))
comm.annos +=["@Id"]
fields += [comm]
}
}
// 处理类名(这⾥是因为我的表都是以t_命名的,所以需要处理去掉⽣成类名时的开头的T,// 如果你不需要那么请查⽤到了 javaClassName这个⽅法的地⽅修改为 javaName 即可)def javaClassName(str, capitalize) {
def s = com.deStyle.NameUtil.splitNameIntoWords(str)
.collect { Case.LOWER.apply(it).capitalize() }
.join("")
.replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
// 去除开头的T developer.51cto/art/200906/129168.htm
// s = s[1..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.deStyle.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 && String().trim().length() > 0
}
static String changeStyle(String str, boolean toCamel){
if(!str || str.size() <= 1)
return str
if(toCamel){
String r = LowerCase().split('_').collect{cc -> Case.LOWER.apply(cc).capitalize()}.join('')
return r[0].toLowerCase() + r[1..-1]
}else{
str = str[0].toLowerCase() + str[1..-1]
llect{cc -> ((char)cc).isUpperCase() ? '_' + cc.toLowerCase() : cc}.join('')
}
}
static String genSerialID()
{
return "\tprivate static final long serialVersionUID = "+Math.abs(new Random().nextLong())+"L;"
}
这时,我们再次选择表,右键,选择我们⾃⼰新建的 vy,然后选择⽣成存放的⽂件夹路径,⽣成:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论