天天看点

MyBatis-18MyBatis代码生成器-Example讲解

文章目录

  • 概述
  • 示例
    • generatorConfig-country.xml
    • 编写Java运行代码
    • 运行获取自动生成的代码
    • 修改 MyBatis全局配置文件 mybatis-config.xml
    • 修改log4j
    • 编写单元测试了解Example的相关用法
      • selectByExample
      • updateByExampleSelective
      • deleteByExample+countByExample

概述

MyBatis-17MyBatis代码生成器(逆向工程)MBG使用中介绍了MBGZ的基本使用。我们知道在MBG的context中将targetRuntime配置为MyBatis3时,MBG会生成和Example相关的对象和方法。 本篇博文我们来介绍下与Example相关的用法。

示例

以country表相关的Example MBG 为例

generatorConfig-country.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="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);
		// 创建 MBG
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		// 执行生成代码
		myBatisGenerator.generate(null);
		// 输出警告信息
		for (String warning : warnings) {
			System.out.println(warning);
		}
		System.out.println("Finshed");
	}

}

           

运行获取自动生成的代码

MyBatis-18MyBatis代码生成器-Example讲解

先粗略了解下自动生成代码结构

CountryExample实体类的结构

MyBatis-18MyBatis代码生成器-Example讲解

CountryMapper接口

MyBatis-18MyBatis代码生成器-Example讲解

CountryMapper.xml

MyBatis-18MyBatis代码生成器-Example讲解

修改 MyBatis全局配置文件 mybatis-config.xml

MyBatis-18MyBatis代码生成器-Example讲解

将配置文件配置到mybatis-config.xml中,因为只有这一个配置文件就直接添加上去了, 如果生成的目录一致,也可以再配置package. 这里mapper.xml和mapper接口目录不一致。所以不采用package的方式了。

修改log4j

MyBatis-18MyBatis代码生成器-Example讲解

为了便于查看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 {

	@Test
	public void countryExampleTest() {
		// 获取sqlSession
		SqlSession 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);
			// 创建条件,只能有一个 createCriteria
			CountryExample.Criteria criteria = example.createCriteria();
			// id >= 1
			criteria.andIdGreaterThanOrEqualTo(1);
			// id < 4
			criteria.andIdLessThan(4);
			// countrycode like '%U%'
			// 最容易出错的地方,注意 like 必须自己写上通配符的位置,不可能默认两边加 %,like 可以是任何情况
			criteria.andCountrycodeLike("%U%");
			// or 的情况,可以有多个 or
			CountryExample.Criteria or = example.or();
			// countryname = 中国
			or.andCountrynameEqualTo("中国");
			// 执行查询
			List<Country> countryList = countryMapper.selectByExample(example);
			printCountryList(countryList);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 不要忘记关闭 sqlSession
			sqlSession.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

@Test
	public void updateByExampleSelectiveTest() {
		// 获取 sqlSession
		SqlSession sqlSession = getSqlSession();
		try {
			// 获取 CountryMapper 接口
			CountryMapper countryMapper = sqlSession.getMapper(CountryMapper.class);
			// 创建 Example 对象
			CountryExample example = new CountryExample();
			// 创建条件,只能有一个 createCriteria
			CountryExample.Criteria criteria = example.createCriteria();
			// 更新所有 id > 2 的国家
			criteria.andIdGreaterThan(2);
			// 创建一个要设置的对象
			Country country = new Country();
			// 将国家名字设置为 China
			country.setCountryname("China");
			// 执行查询
			countryMapper.updateByExampleSelective(country, example);
			// 在把符合条件的结果输出查看
			printCountryList(countryMapper.selectByExample(example));
		} finally {
			// 为了不影响数据,这里选择回滚
			sqlSession.rollback();
			// 不要忘记关闭 sqlSession
			sqlSession.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

@Test
	public void deleteByExampleTest() {
		// 获取 sqlSession
		SqlSession sqlSession = getSqlSession();
		try {
			// 获取 CountryMapper 接口
			CountryMapper countryMapper = sqlSession.getMapper(CountryMapper.class);
			// 创建 Example 对象
			CountryExample example = new CountryExample();
			// 创建条件,只能有一个 createCriteria
			CountryExample.Criteria criteria = example.createCriteria();
			// 删除所有 id > 2 的国家
			criteria.andIdGreaterThan(2);
			// 执行查询
			countryMapper.deleteByExample(example);
			// 使用 countByExample 查询符合条件的数量,因为删除了,所以这里应该是 0
			Assert.assertEquals(0, countryMapper.countByExample(example));
		} finally {
			// 为了不影响数据,这里选择回滚
			sqlSession.rollback();
			// 不要忘记关闭 sqlSession
			sqlSession.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