快速生成實體類介紹
快速生成實體類有多種方式,這次主要介紹兩種:
1、idea 從數據庫快速生成Spring Data JPA實體類。
2、通過Mybatis generator工具生成實體類。
-
idea 從數據庫快速生成Spring Data JPA實體類
方法一 通過groovy模板快速生成
配置數據庫
view -> Tool Windows -> Database
+ -> Data source -> Oracle(其他數據庫同理)
配置數據庫信息
建立存放實體的包
導入必要maven依賴
如果是oracle數據庫,添加oracle依賴
<!-- 添加oracle驅動依賴 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.1.0</version>
</dependency>
如果是mysql,添加mysql依賴
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
其他依賴
<!--jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
在database視圖區域任意地方右鍵,然後Scripted Extensions -> Go to Scripts Directory
若沒有Generate POJOs.groovy文件,新增Generate POJOs.groovy文件。 Groovy 模板引擎
文件內容爲:
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 + ".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]
}
在database視圖區域選擇你想要生成的表,然後Scripted Extensions -> Generate POJOs.groovy 可以使用Shift和Ctrl多選
方法二 通過Persistence快速生成
配置數據庫連接同上(方法一中的數據庫連接)
調出 Persistence 窗口
配置數據庫連接同上(方法一中的數據庫連接)
調出 Persistence 窗口
File—>Project Structure—>model—> + —>JPA
打開 Persistence窗口
配置生成實體類的參數
1.數據源,即鏈接數據庫的信息,按要求填寫數據庫信息即可
2.生成實體類的位置.
3.實體類名稱前綴.
4.實體類名稱後綴. 這裏我寫Entity. 比如數據庫表名爲 user,那麼生成實體類爲 UserEntity
5.選擇哪些表的哪些字段生成實體類.這裏我全選.
6.生成的實體類自動添加 JPA註解.
-
通過Mybatis generator工具生成實體類
方法一:通過idea自動生成
選擇上面配置的數據源,並在中找到需要生成的對應的數據庫表。
選擇mybatis-generator,並制定對應entity,dao,mapper的生成位置。
方法二:
1、IDEA創建maven工程(略)
2、 在maven項目的pom.xml 添加mybatis-generator-maven-plugin 插件和MySQL數據庫驅動依賴
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
3、在maven項目下的src/main/resources 目錄下建立名爲 generatorConfig.xml的配置文件,作爲mybatis-generator-maven-plugin 插件的執行目標,模板如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 配置mysql 驅動jar包路徑.用了絕對路徑 -->
<classPathEntry location="C:\Users\zhangbo\.m2\repository\mysql\mysql-connector-java\5.1.25\mysql-connector-java-5.1.25.jar" />
<context id="emil_mysql_tables">
<!-- 防止生成的代碼中有很多註釋,加入下面的配置控制 -->
<commentGenerator>
<!-- 刪除代碼中帶有 代碼生成器的註釋信息 -->
<property name="suppressAllComments" value="true" />
<property name="suppressDate" value="true" />
</commentGenerator>
<jdbcConnection connectionURL="jdbc:mysql://127.0.0.1:3306/emiltest" driverClass="com.mysql.jdbc.Driver" password="123456" userId="root" />
<!-- 數據表對應的model層 -->
<javaModelGenerator targetPackage="com.emil.shiro.entity" targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- sql mapper 映射配置文件 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- mybatis3中的mapper接口 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.emil.shiro.dao" targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!--
<table tableName=""></table>
--> <!-- 數據表進行生成操作 schema:相當於庫名; tableName:表名; domainObjectName:對應的DO domainObjectName="SysAccessPermission"-->
<table tableName="om_menu" schema="emiltest" enableSelectByExample="false" enableDeleteByExample="false" enableCountByExample="false" enableUpdateByExample="fasle" />
<table tableName="om_user" schema="emiltest" enableSelectByExample="false" enableDeleteByExample="false" enableCountByExample="false" enableUpdateByExample="fasle" ></table>
<table tableName="om_role" schema="emiltest" enableSelectByExample="false" enableDeleteByExample="false" enableCountByExample="false" enableUpdateByExample="fasle" ></table>
<table tableName="om_permis" schema="emiltest" enableSelectByExample="false" enableDeleteByExample="false" enableCountByExample="false" enableUpdateByExample="fasle" ></table>
<table tableName="role_permis" schema="emiltest" enableSelectByExample="false" enableDeleteByExample="false" enableCountByExample="false" enableUpdateByExample="fasle" ></table>
<table tableName="user_role" schema="emiltest" enableSelectByExample="false" enableDeleteByExample="false" enableCountByExample="false" enableUpdateByExample="fasle" ></table>
</context>
</generatorConfiguration>
MyBatis Generator 詳解。參考:
https://blog.csdn.net/isea533/article/details/42102297
4、使用maven運行mybatis-generator-maven-plugin插件:工程名->Plugins->mybatis-generator->mybatis-generator:generate->Run Maven Build
5、自動生成的結構如下:
如果你覺得這篇文章對你有幫助或啓發,也可以來請我喝咖啡。