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="https://www.cnblogs.com/heihaozi/p/UTF-8"/>
<!-- 生成的物體類實作序列化介面 -->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<commentGenerator>
<property name="dateFormat" value="https://www.cnblogs.com/heihaozi/p/yyyy-MM-dd HH:mm:ss"/>
</commentGenerator>
<!--資料庫連接資訊-->
<jdbcConnection driver
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="https://www.cnblogs.com/heihaozi/p/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必讀技術書籍
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/219731.html
標籤:Java
上一篇:C語言環境搭建
下一篇:安裝JDK
