MyBatis Generator簡介
業務需求不斷變更,數據庫表結構不斷修改,是我們逃不出的宿命。工欲善其事,必先利其器,是時候祭出神器了:MyBatis Generator(簡稱:MBG),它是一個用於所有版本MyBatis的代碼自動生成器。它可以根據數據庫的表自動為項目生產對應的實體類、Mapper、DAO,包括簡單CRUD數據庫操作(創建、查詢、更新、刪除)。解放了我們的雙手,不必做重復性的機械工作。節省下不少時間,不用再苦哈哈的加班了,還可以和妹紙去約會。(前提是你得先有個妹紙🤐)
創建一個MySQL表
為了方便演示創建一個MySQL表,表結構比較簡單,是一個用戶信息表:
CREATE TABLE `user_info` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
文章持續更新,微信搜索「萬貓學社第一時間閱讀,關注后回復「電子書」,免費獲取12本Java必讀技術書籍。
創建一個SpringBoot項目
以使用IntelliJ IDEA為例,創建一個SpringBoot項目。點擊File->New->Projects...,選擇Spring Initializr,如下圖:

點擊Next,輸入Group、Artifact等信息,如下圖:

點擊Next,選擇Web,並勾選Spring Web,如下圖:

點擊Next,輸入Project name、Project location等信息,如下圖:

最后,點擊Finish,一個SpringBoot項目就創建完了。
引入MyBatis Generator的Maven插件
在pom.xml的plugins節點中添加如下內容:
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
</plugin>
配置MyBatis Generator的Maven插件
在resources文件夾中創建一個generatorConfig.xml文件,其內容如下:
<?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"></properties>
<!--defaultModelType用於指定生成對象的樣式,flat表示每一張表只生成一個實體類,這個實體類包含表中的所有字段。-->
<context id="MySQLTables" targetRuntime="MyBatis3" defaultModelType="flat">
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 生成的實體類實現序列化接口 -->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<commentGenerator>
<property name="dateFormat" value="yyyy-MM-dd HH:mm:ss"/>
</commentGenerator>
<!--數據庫連接信息-->
<jdbcConnection driverClass="${spring.datasource.driverClassName}"
connectionURL="${spring.datasource.url}"
userId="${spring.datasource.username}"
password="${spring.datasource.password}">
</jdbcConnection>
<!-- 配置生成的實體類位置 -->
<javaModelGenerator targetPackage="one.more.mybatisgenerator.model" targetProject="src/main/java">
<!-- 設置是否在setter方法中,對String類型字段調用trim()方法 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 配置接口位置 -->
<!-- type設置為ANNOTATEDMAPPER,基於注解的Mapper,不會有對應的xml文件生成-->
<javaClientGenerator targetPackage="one.more.mybatisgenerator.mapper" targetProject="src/main/java"
type="ANNOTATEDMAPPER">
</javaClientGenerator>
<!-- 配置數據庫表 -->
<table tableName="user_info">
<!--在生成的insert元素上添加useGeneratedKeys=”true”和keyProperty屬性-->
<generatedKey column="id" sqlStatement="JDBC"/>
</table>
</context>
</generatorConfiguration>
以上就是最基礎簡介的配置了,在實際的開發過程中就夠用。如果有小伙伴還有需要更多的配置功能,可以官方網站(https://mybatis.org/generator/configreference/xmlconfig.html)查看。
文章持續更新,微信搜索「萬貓學社第一時間閱讀,關注后回復「電子書」,免費獲取12本Java必讀技術書籍。
自動生成代碼
下面就是最激動人心的時刻了,一鍵自動生成代碼。在Maven插件工具欄中,可以看到mybatis-generator插件,雙擊其中的generate選項即可,如下圖:

構建成功以后,就可以看到生成的代碼了,如下圖:

驗證自動生成的代碼
驗證之前還有一個步驟不要漏掉,就是在啟動類上加上MapperScan注解,比如:
@SpringBootApplication
@MapperScan("one.more.mybatisgenerator.mapper")
public class MybatisGeneratorDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisGeneratorDemoApplication.class, args);
}
}
文章持續更新,微信搜索「萬貓學社第一時間閱讀,關注后回復「電子書」,免費獲取12本Java必讀技術書籍。
新增數據
隨機生成一個UserInfo示例,插入到數據庫中:
public UserInfo add() {
Random random = new Random(System.currentTimeMillis());
UserInfo userInfo = new UserInfo();
userInfo.setName("name" + random.nextInt(100));
userInfo.setAge(random.nextInt(100));
userInfo.setCreateTime(new Date());
int rows = userInfoMapper.insert(userInfo);
System.out.println("rows:" + rows);
return userInfo;
}
查詢數據
查詢數據庫里age大於某個值的user_info數據:
public List<UserInfo> getGreaterThan(Integer age) {
UserInfoExample example = new UserInfoExample();
Criteria criteria = example.createCriteria();
criteria.andAgeGreaterThan(age);
return userInfoMapper.selectByExample(example);
}
完整的示例源碼
完整的示例源碼可以去https://github.com/heihaozi/mybatis-generator-demo下載。
微信公眾號:萬貓學社
微信掃描二維碼
關注后回復「電子書」
獲取12本Java必讀技術書籍
