MyBatis代码生成器-Example讲解
概述
在上篇博文 MyBatis代碼生成器(逆向工程)MBG使用?中介紹了MBGZ的基本使用。我們知道在MBG的context中將targetRuntime配置為MyBatis3時,MBG會生成和Example相關的對象和方法。 本篇博文我們來介紹下與Example相關的用法。
示例
以country表相關的Example MBG 為例
generatorConfig-country.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><!-- 配置生成器 --> <generatorConfiguration>?<!-- 引用外部配置文件 --><properties resource="db.properties" /><!--?在MBG工作的時候,需要額外加載的依賴包location屬性指明加載jar/zip包的全路徑 --><!--<classPathEntry location="F:\.m2\repository\mysql\mysql-connector-java\5.1.38\mysql-connector-java-5.1.38.jar"/>--><context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat"><!-- beginningDelimiter/endingDelimiter: 指明數據庫的用于標記數據庫對象名的符號,比如ORACLE是雙引號,MYSQL默認是`反引號 ?--><property name="beginningDelimiter" value="`"/><property name="endingDelimiter" value="`"/><!-- 生成的Java文件的編碼 --><property name="javaFileEncoding" value="UTF-8"/><commentGenerator><!-- suppressDate是去掉生成日期那行注釋,suppressAllComments是去掉所有的注解 --><property name="suppressDate" value="true"/><!-- 在生成的實體類中附帶表字段的注釋 ?MBG1.3.3中新增的功能 --><property name="addRemarkComments" value="true"/></commentGenerator><!-- 必須存在,使用這個配置鏈接數據庫--><jdbcConnection driverClass="${jdbc.driver}"connectionURL="${jdbc.url}"userId="${jdbc.username}"password="${jdbc.password}"><!-- 這里面可以設置property屬性,每一個property屬性都設置到配置的Driver上 --></jdbcConnection><javaModelGenerator targetPackage="example.model" targetProject="src\main\java"><!-- 設置是否在getter方法中,對String類型字段調用trim()方法 --><property name="trimStrings" value="true" /></javaModelGenerator><sqlMapGenerator targetPackage="example.xml" ?targetProject="src\main\resources"></sqlMapGenerator><javaClientGenerator type="XMLMAPPER" targetPackage="example.dao" ?targetProject="src\main\java"></javaClientGenerator><table tableName="country"><generatedKey column="id" sqlStatement="MySql"/></table></context> </generatorConfiguration>
編寫Java運行代碼
package com.mybatis.generator;import java.io.InputStream; import java.util.ArrayList; import java.util.List;import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback;/***?*?* @ClassName: GeneratorCountry*?* @Description: 讀取 MBG 配置生成代碼*?* @author: Mr.Yang*?* @date: 2018年4月27日 下午23:31:42*/ public class GeneratorCountry {public static void main(String[] args) throws Exception {// MBG 執行過程中的警告信息List<String> warnings = new ArrayList<String>();// 當生成的代碼重復時,覆蓋原代碼boolean overwrite = true;// 讀取MBG配置文件InputStream is = GeneratorCountry.class.getResourceAsStream("/generator/generatorConfig-country.xml");ConfigurationParser cp = new ConfigurationParser(warnings);Configuration config = cp.parseConfiguration(is);is.close();DefaultShellCallback callback = new DefaultShellCallback(overwrite);// 創建 MBGMyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);// 執行生成代碼myBatisGenerator.generate(null);// 輸出警告信息for (String warning : warnings) {System.out.println(warning);}System.out.println("Finshed");}}
運行獲取自動生成的代碼
先粗略了解下自動生成代碼結構
?
?
CountryExample實體類的結構?
CountryMapper接口?
CountryMapper.xml?
?
修改 MyBatis全局配置文件 mybatis-config.xml
將配置文件配置到mybatis-config.xml中,因為只有這一個配置文件就直接添加上去了, 如果生成的目錄一致,也可以再配置package. 這里mapper.xml和mapper接口目錄不一致。所以不采用package的方式了。
?
修改log4j
為了便于查看mybatis的內部執行過程,添加如上代碼
?
編寫單元測試了解Example的相關用法
selectByExample
package example.dao;import java.util.List;import org.apache.ibatis.session.SqlSession; import org.junit.Test;import com.artisan.mybatis.xml.mapper.BaseMapperTest;import example.model.Country; import example.model.CountryExample;public class CountryMapperTest extends BaseMapperTest {@Testpublic void countryExampleTest() {// 獲取sqlSessionSqlSession sqlSession = getSqlSession();try {// 獲取 CountryMapper 接口CountryMapper countryMapper = sqlSession.getMapper(CountryMapper.class);// 創建 Example 對象CountryExample example = new CountryExample();// 設置排序規則example.setOrderByClause("id desc, countryname asc");// 設置是否 distinct 去重example.setDistinct(true);// 創建條件,只能有一個 createCriteriaCountryExample.Criteria criteria = example.createCriteria();// id >= 1criteria.andIdGreaterThanOrEqualTo(1);// id < 4criteria.andIdLessThan(4);// countrycode like '%U%'// 最容易出錯的地方,注意 like 必須自己寫上通配符的位置,不可能默認兩邊加 %,like 可以是任何情況criteria.andCountrycodeLike("%U%");// or 的情況,可以有多個 orCountryExample.Criteria or = example.or();// countryname = 中國or.andCountrynameEqualTo("中國");// 執行查詢List<Country> countryList = countryMapper.selectByExample(example);printCountryList(countryList);} catch (Exception e) {e.printStackTrace();} finally {// 不要忘記關閉 sqlSessionsqlSession.close();}}private void printCountryList(List<Country> countryList) {for (Country country : countryList) {System.out.printf("%-4d%4s%4s\n", country.getId(), country.getCountryname(), country.getCountrycode());}}}除了代碼中注釋內容外,特別需要注意的地方是or的方法。 當有多個or的時候,SQL語句就是類似 or(…) or(…)這樣的SQL,如果一個or都沒有,那就只有example.createCriteria()中的查詢條件。
日志
2018-04-28 15:43:09,468 ?INFO [main] (BaseMapperTest.java:26) - sessionFactory bulit successfully 2018-04-28 15:43:09,468 ?INFO [main] (BaseMapperTest.java:29) - reader close successfully 2018-04-28 15:43:09,677 DEBUG [main] (BaseJdbcLogger.java:145) - ==> ?Preparing: select distinct id, countryname, countrycode from country WHERE ( id >= ? and id < ? and countrycode like ? ) or( countryname = ? ) order by id desc, countryname asc? 2018-04-28 15:43:09,777 DEBUG [main] (BaseJdbcLogger.java:145) - ==> Parameters: 1(Integer), 4(Integer), %U%(String), 中國(String) 2018-04-28 15:43:09,817 TRACE [main] (BaseJdbcLogger.java:151) - <== ? ?Columns: id, countryname, countrycode 2018-04-28 15:43:09,817 TRACE [main] (BaseJdbcLogger.java:151) - <== ? ? ? ?Row: 3, 俄羅斯, RU 2018-04-28 15:43:09,817 TRACE [main] (BaseJdbcLogger.java:151) - <== ? ? ? ?Row: 2, 美國, US 2018-04-28 15:43:09,817 TRACE [main] (BaseJdbcLogger.java:151) - <== ? ? ? ?Row: 1, 中國, CN 2018-04-28 15:43:09,817 DEBUG [main] (BaseJdbcLogger.java:145) - <== ? ? ?Total: 3 3 ? ?俄羅斯 ?RU 2 ? ? 美國 ?US 1 ? ? 中國 ?CN
updateByExampleSelective
@Testpublic void updateByExampleSelectiveTest() {// 獲取 sqlSessionSqlSession sqlSession = getSqlSession();try {// 獲取 CountryMapper 接口CountryMapper countryMapper = sqlSession.getMapper(CountryMapper.class);// 創建 Example 對象CountryExample example = new CountryExample();// 創建條件,只能有一個 createCriteriaCountryExample.Criteria criteria = example.createCriteria();// 更新所有 id > 2 的國家criteria.andIdGreaterThan(2);// 創建一個要設置的對象Country country = new Country();// 將國家名字設置為 Chinacountry.setCountryname("China");// 執行查詢countryMapper.updateByExampleSelective(country, example);// 在把符合條件的結果輸出查看printCountryList(countryMapper.selectByExample(example));} finally {// 為了不影響數據,這里選擇回滾sqlSession.rollback();// 不要忘記關閉 sqlSessionsqlSession.close();}}
我們看CountryMapper接口,可以看到有 updateByExample和updateByExampleSelective。 這兩個方法的區別是,當對象的屬性為空的時候,第一個方法會將值更新為null , 第二個方法不會更新null屬性的字段。 通過Example一般都是批量操作,由于country表存在主鍵id,不能被批量更新, 因此要使用updateByExampleSelective方法進行測試。
日志
2018-04-28 15:47:24,736 ?INFO [main] (BaseMapperTest.java:26) - sessionFactory bulit successfully 2018-04-28 15:47:24,736 ?INFO [main] (BaseMapperTest.java:29) - reader close successfully 2018-04-28 15:47:24,967 DEBUG [main] (BaseJdbcLogger.java:145) - ==> ?Preparing: update country SET countryname = ? WHERE ( id > ? )? 2018-04-28 15:47:25,083 DEBUG [main] (BaseJdbcLogger.java:145) - ==> Parameters: China(String), 2(Integer) 2018-04-28 15:47:25,083 DEBUG [main] (BaseJdbcLogger.java:145) - <== ? ?Updates: 3 2018-04-28 15:47:25,093 DEBUG [main] (BaseJdbcLogger.java:145) - ==> ?Preparing: select id, countryname, countrycode from country WHERE ( id > ? )? 2018-04-28 15:47:25,093 DEBUG [main] (BaseJdbcLogger.java:145) - ==> Parameters: 2(Integer) 2018-04-28 15:47:25,123 TRACE [main] (BaseJdbcLogger.java:151) - <== ? ?Columns: id, countryname, countrycode 2018-04-28 15:47:25,123 TRACE [main] (BaseJdbcLogger.java:151) - <== ? ? ? ?Row: 3, China, RU 2018-04-28 15:47:25,123 TRACE [main] (BaseJdbcLogger.java:151) - <== ? ? ? ?Row: 4, China, GB 2018-04-28 15:47:25,123 TRACE [main] (BaseJdbcLogger.java:151) - <== ? ? ? ?Row: 5, China, FR 2018-04-28 15:47:25,123 DEBUG [main] (BaseJdbcLogger.java:145) - <== ? ? ?Total: 3 3 ? China ?RU 4 ? China ?GB 5 ? China ?FR
deleteByExample+countByExample
@Testpublic void deleteByExampleTest() {// 獲取 sqlSessionSqlSession sqlSession = getSqlSession();try {// 獲取 CountryMapper 接口CountryMapper countryMapper = sqlSession.getMapper(CountryMapper.class);// 創建 Example 對象CountryExample example = new CountryExample();// 創建條件,只能有一個 createCriteriaCountryExample.Criteria criteria = example.createCriteria();// 刪除所有 id > 2 的國家criteria.andIdGreaterThan(2);// 執行查詢countryMapper.deleteByExample(example);// 使用 countByExample 查詢符合條件的數量,因為刪除了,所以這里應該是 0Assert.assertEquals(0, countryMapper.countByExample(example));} finally {// 為了不影響數據,這里選擇回滾sqlSession.rollback();// 不要忘記關閉 sqlSessionsqlSession.close();}}
日志
2018-04-28 15:49:43,236 ?INFO [main] (BaseMapperTest.java:26) - sessionFactory bulit successfully
2018-04-28 15:49:43,266 ?INFO [main] (BaseMapperTest.java:29) - reader close successfully
2018-04-28 15:49:43,503 DEBUG [main] (BaseJdbcLogger.java:145) - ==> ?Preparing: delete from country WHERE ( id > ? )?
2018-04-28 15:49:43,633 DEBUG [main] (BaseJdbcLogger.java:145) - ==> Parameters: 2(Integer)
2018-04-28 15:49:43,643 DEBUG [main] (BaseJdbcLogger.java:145) - <== ? ?Updates: 3
2018-04-28 15:49:43,653 DEBUG [main] (BaseJdbcLogger.java:145) - ==> ?Preparing: select count(*) from country WHERE ( id > ? )?
2018-04-28 15:49:43,653 DEBUG [main] (BaseJdbcLogger.java:145) - ==> Parameters: 2(Integer)
2018-04-28 15:49:43,693 TRACE [main] (BaseJdbcLogger.java:151) - <== ? ?Columns: count(*)
2018-04-28 15:49:43,693 TRACE [main] (BaseJdbcLogger.java:151) - <== ? ? ? ?Row: 0
2018-04-28 15:49:43,693 DEBUG [main] (BaseJdbcLogger.java:145) - <== ? ? ?Total: 1
通過上述幾個例子,應該對example有所了解了。 使用Example查詢能夠解決大部分復雜的單表操作,一定程度上減少工作量。 但是建議在條件很多并且判斷很多的情況下,避免使用Example查詢, 這種情況下,使用XML方式會更有效。
---------------------?
作者:小小工匠?
來源:CSDN?
原文:https://blog.csdn.net/yangshangwei/article/details/80140693?
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
總結
以上是生活随笔為你收集整理的MyBatis代码生成器-Example讲解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MyBatis代码生成器(逆向工程)MB
- 下一篇: 程序员也得懂点儿理财知识