MyBatis是Java目前主流的ORM框架,在Spring Boot中使用MyBatis能夠參考這篇文章:http://www.ityouknow.com/springboot/2016/11/06/spring-boot-mybatis.htmlhtml
這篇文章來將介紹MyBatis Generator,(簡稱MBG,下文使用這個簡稱),該插件能夠很方便的生成實體類、Mapper接口代碼等,提升開發效率,它有點像.NET的EF框架中的DB First。另外,順便介紹Spring Boot如何集成Swagger。java
(1)既然是像EF的DB First,那須要先建好數據庫,能夠先在MySQL中執行如下SQL腳本:mysql
create database generatortest default character set utf8mb4 collate utf8mb4_unicode_ci; use generatortest; create user 'generatortest'@'localhost' identified by 'generatortest123'; grant all privileges on generatortest.* to 'generatortest'@'localhost'; flush privileges; CREATE TABLE `user` ( id INT NOT NULL AUTO_INCREMENT COMMENT '用戶ID', user_name VARCHAR(50) NOT NULL COMMENT '用戶名', `password` VARCHAR(50) NOT NULL COMMENT '密碼', email VARCHAR(50) COMMENT '郵箱', avatar VARCHAR(255) COMMENT '頭像', create_time DATETIME NOT NULL COMMENT '建立時間', update_time DATETIME NOT NULL COMMENT '更新時間', deleted TINYINT(1) default 0 COMMENT '邏輯刪除', PRIMARY KEY (id) ); ALTER TABLE `user` COMMENT '用戶表'; CREATE TABLE role ( id INT NOT NULL AUTO_INCREMENT COMMENT '角色ID', role_name VARCHAR(50) NOT NULL COMMENT '角色名', enabled TINYINT(1) default 1 NOT NULL COMMENT '有效標誌', create_time DATETIME NOT NULL COMMENT '建立時間', update_time DATETIME NOT NULL COMMENT '更新時間', deleted TINYINT(1) default 0 NOT NULL COMMENT '邏輯刪除', PRIMARY KEY (id) ); ALTER TABLE role COMMENT '角色表'; CREATE TABLE permission ( id INT NOT NULL AUTO_INCREMENT COMMENT '權限ID', permission_name VARCHAR(50) NOT NULL COMMENT '權限名稱', permission_value VARCHAR(200) NOT NULL COMMENT '權限值', PRIMARY KEY (id) ); ALTER TABLE permission COMMENT '權限表'; CREATE TABLE user_role ( user_id INT NOT NULL COMMENT '用戶ID', role_id INT NOT NULL COMMENT '角色ID' ); ALTER TABLE user_role COMMENT '用戶角色關聯表'; CREATE TABLE role_permission ( role_id INT NOT NULL COMMENT '角色ID', permission_id INT NOT NULL COMMENT '權限ID' ); ALTER TABLE role_permission COMMENT '角色權限關聯表';
(2)新建Maven項目,還不知道怎麼用VS Code建Maven項目的能夠參考這篇文章;git
(3)添加相關Maven文件:github
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.7</version> </dependency>
(1)在application.properties文件中添加MySQL數據鏈接配置:web
spring.datasource.url=jdbc:mysql://localhost:3306/generatortest?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true spring.datasource.username=generatortest spring.datasource.password=generatortest123 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
(2)在src\main\resources目錄下新建generatorConfig.xml配置文件,添加以下配置:spring
<?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> <properties resource="application.properties"/> <context id="MySqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat"> <!-- 當表名或者字段名爲SQL關鍵字的時候,能夠設置該屬性爲true,MBG會自動給表名或字段名添加**分隔符**。默認值爲false --> <property name="autoDelimitKeywords" value="true"/> <!--可使用``包括字段名,避免字段名與sql保留字衝突報錯,默認值爲雙引號"""--> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <!-- 自動生成toString方法 --> <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/> <!-- 爲模型生成序列化方法--> <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/> <commentGenerator> <property name="suppressDate" value="true"/> <!--<property name="suppressAllComments" value="true"/>--> </commentGenerator> <jdbcConnection driverClass="${spring.datasource.driver-class-name}" connectionURL="${spring.datasource.url}" userId="${spring.datasource.username}" password="${spring.datasource.password}"> <!--解決mysql驅動升級到8.0後不生成指定數據庫代碼的問題--> <property name="nullCatalogMeansCurrent" value="true" /> </jdbcConnection> <javaTypeResolver> <property name="useJSR310Types" value="true"/> </javaTypeResolver> <javaModelGenerator targetPackage="com.example.demo.model" targetProject="src/main/java"/> <javaClientGenerator type="ANNOTATEDMAPPER" targetPackage="com.example.demo.mapper" targetProject="src/main/java" /> <!-- 生成全部表 --> <table tableName="%" > <generatedKey column="id" sqlStatement="Mysql" identity="true"/> </table> </context> </generatorConfiguration>
接下來分析generatorConfig.xml配置:sql
<properties> 元素數據庫
非必選元素,用於指定一個須要在配置中解析使用的外部屬性文件。這裏引入application.properties配置文件,下文<jdbcConnection> 元素用到;api
<context > 元素
必選元素,能夠有多個,用必選屬性id區分;
targetRuntime屬性:默認值爲MyBatis3;
MyBatis3:MBG將生成與MyBatis 3.0及以上版本兼容的對象,以及與JSE 5.0及以上版本兼容的對象。同時生成「by example」方法,用於構建動態where字句;
MyBatis3Simple:比MyBatis3少生成「by example」方法;
defaultModelType屬性:值爲flat時,每一張表只生成一個實體類,這個實體類包含表中的全部字段;
<property> 元素
非必選元素,如下三個屬性設置是針對MySQL數據庫的:
<!-- 當表名或者字段名爲SQL關鍵字的時候,能夠設置該屬性爲true,MBG會自動給表名或字段名添加**分隔符**。默認值爲false --> <property name="autoDelimitKeywords" value="true"/> <!--可使用``包括字段名,避免字段名與sql保留字衝突報錯,默認值爲雙引號"""--> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/>
假設在Mysql數據庫中有一個表名爲user detail,中間是一個空格,這種狀況下若是寫出select * from user detail這樣的語句,是會報錯的;
Mysql中,通常會寫成樣子:select * from `user detail `
以上三個配置屬性就是當表名或者字段名爲SQL關鍵字時,自動加 ` 先後分隔符;
<plugin> 元素
非必選元素,用來定義一個插件。插件用於擴展或修改MBG代碼生成器生成的代碼;
<commentGenerator> 元素
非必選元素,最多配置一個;
suppressAllComments屬性:值爲true時,阻止生成註釋,默認爲false;
suppressDate屬性:值爲true時,阻止生成包含時間戳的註釋,默認爲false;
<jdbcConnection> 元素
必選元素,且只能有一個,用於指定數據庫鏈接信息;
driverClass:必選屬性,訪問數據庫的JDBC驅動程序的徹底限定類名;
connectionURL:必選屬性,訪問數據庫的JDBC鏈接URL;
userId:非必選屬性,訪問數據庫的用戶ID;
Password:非必選屬性,訪問數據庫的密碼;
<javaTypeResolver> 元素
非必選元素,最多配置一個,用於指定JDBC類型和Java類型如何轉換;
useJSR310Types:當值爲true時,會進行以下轉換,其中java.time.LocalDateTime和.NET中的DateTime最爲類似;
JDBC Type |
Resolved Java Type |
DATE |
java.time.LocalDate |
TIME |
java.time.LocalTime |
TIMESTAMP |
java.time.LocalDateTime |
<javaModelGenerator> 元素
必選元素,並且最多一個,用於控制生成的實體類;
targetPackage:必選屬性,生成實體類存放的包名;
targetProject:必選屬性,指定targetPackage路徑,能夠是絕對路徑或相對路徑;
<javaClientGenerator> 元素
非必選元素,最多配置一個,用於生成Mapper接口代碼,不配置就不生成;
Type=」 ANNOTATEDMAPPER」:生成基於註解的Mapper接口,不會有對應的XML映射文件;
Type=」 XMLMAPPER」:全部的方法都在XML中,接口調用依賴XML文件;
targetPackage:必選屬性,生成Mapper接口代碼存放的包名;
targetProject:必選屬性,指定targetPackage路徑,能夠是絕對路徑或相對路徑;
<table> 元素
必選元素,能夠有多個,tableName="%"時生成全部表;
子元素<generatedKey>,可選元素,最多一個,用於指定自動生成主鍵的屬性;
Column:必選屬性,生成列的列名;
sqlStatement:必選屬性,使用一個預約義的的值返回新的SQL語句;
Identity:可選屬性,是否爲惟一標誌列,默認爲false;
(1)在項目中建立Generator類,添加一個main方法,寫上以下代碼:
public static void main(String[] args) throws Exception { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration( Generator.class.getResourceAsStream("/generatorConfig.xml")); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); }
(2)點擊Run,能夠看到生成的實體類和Mapper接口代碼
生成代碼結構
(1)pom.xml中添加以下配置,而後保存;
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency>
(2)編寫控制器代碼,調用MBG生成的Mapper接口代碼
@RestController public class UserController { @Autowired private UserMapper userMapper; @RequestMapping(value = "/getUsers", method=RequestMethod.GET) public List<User> getUsers() { List<User> users=userMapper.selectAll(); return users; } @RequestMapping(value = "/getUser", method=RequestMethod.GET) public User getUser(Integer id) { User user=userMapper.selectByPrimaryKey(id); return user; } @RequestMapping(value = "/add", method=RequestMethod.POST) public void save(User user) { if(user.getCreateTime()==null) user.setCreateTime(LocalDateTime.now(Clock.system(ZoneId.of("Asia/Shanghai")))); if(user.getUpdateTime() == null) user.setUpdateTime(LocalDateTime.now(Clock.system(ZoneId.of("Asia/Shanghai")))); userMapper.insert(user); } @RequestMapping(value = "update", method=RequestMethod.PUT) public void update(User user) { userMapper.updateByPrimaryKey(user); } @RequestMapping(value = "/delete/{id}", method=RequestMethod.DELETE) public void delete(@PathVariable("id") Integer id) { userMapper.deleteByPrimaryKey(id); } }
其中UserMapper經過註解@Autowired注入進來。
(3)在application.properties配置文件中加上:
(4)在啓動類中添加對 mapper 包掃描@MapperScan
(1)pom.xml中添加支持swagger的模塊,而後保存。
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
(2)添加SwaggerConfig配置文件:
public class SwaggerConfig { @Bean public Docket swaggerSpringMvcPlugin() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build(); } }
(3)爲每一個接口添加@ApiOperation註解,以下:
@ApiOperation(value = "獲取全部用戶信息" , notes = "返回全部用戶信息")
最後運行程序,瀏覽器打開:http://localhost:8080/swagger-ui.html
源碼地址:https://github.com/Bingjian-Zhu/MybatisGeneatorDemo.git