mybatis学习5

一、MyBatis Generator配置:
数据库表结构可查看mybatis学习2
1、使用 Maven Plugin 运行。

在src/main/resources/generator目录下新建:generatorConfig.xml。
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>

    <!--指定特定数据库的jdbc驱动jar包的位置 -->
    <classPathEntry location="/path/to/maven/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar"/>
   
    <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <!-- 旨在创建class时,对注释进行控制 -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>

        <!--jdbc的数据库连接 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/learnmybatis?useSSL=false"
            userId="root"
            password="123456">
        </jdbcConnection>


        <javaModelGenerator targetPackage="cn.linst.model" targetProject="src/main/java">
            <!-- 设置是否在getter方法中,对String类型字段调用trim()方法 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--指定sql映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="cn.linst.mapper" targetProject="src/main/resources">
            <!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- 指定dao接口生成的位置,mapper接口 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="cn.linst.dao" targetProject="src/main/java"/>

        <table tableName="country">
            <generatedKey column="id" sqlStatement="MySql"/>
        </table>
    </context>
</generatorConfiguration>
<context> 中将 targetRuntime 配置为 MyBatis3 时,MBG 会生成和 Example相关的对象和方法。

<table tableName="country"> country表。
如果要全部的表, 设置成 "%"

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!-- 省略其他-->
	<build>
	 	<plugins>
	      <plugin>
	        <groupId>org.mybatis.generator</groupId>
	        <artifactId>mybatis-generator-maven-plugin</artifactId>
	        <version>1.3.3</version>
	        <configuration>
	          <configurationFile>
	            ${basedir}/src/main/resources/generator/generatorConfig.xml
	          </configurationFile>
	          <overwrite>true</overwrite>
	          <verbose>true</verbose>
	        </configuration>
	        <dependencies>
	          <dependency>
	            <groupId>mysql</groupId>
	            <artifactId>mysql-connector-java</artifactId>
	            <version>5.1.38</version>
	          </dependency>
	          <!--<dependency>-->
	            <!--<groupId>cn.linst</groupId>-->
	            <!--<artifactId>learnmybatis</artifactId>-->
	          <!--</dependency>-->
	        </dependencies>
	      </plugin>
	    </plugins>
	</build>
</project>

运行maven插件,在maven双击运行:
在这里插入图片描述
或者在项目根目录运行命令,即可生成:

mvn mybatis-generator:generate

2、Example相关使用,如下测试方法:

generatorConfig.xml:文件中,当<context> 中将 targetRuntime 配置为 MyBatis3 时,MBG 会生成和 Example相关的对象和方法。
package cn.linst;

import cn.linst.dao.CountryMapper;
import cn.linst.model.Country;
import cn.linst.model.CountryExample;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.io.Reader;
import java.util.List;


public class CountryMapperTest extends BaseMapperTest{
    
    
	@Test
    public void testExample () {
    
    
        //获取 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);
            //创建条件
            CountryExample.Criteria criteria = example.createCriteria();
            //id >= 1
            criteria.andIdGreaterThanOrEqualTo(1);
            //id< 4
            criteria.andIdLessThan(4);
            //countrycode like
            //最容易 出错的地方,注意 like 必须自己写上通配符的位直
            criteria.andCountrycodeLike("%U%");
            //or 的情况
            CountryExample.Criteria or = example.or();
            //countryname 中国
            or.andCountrynameEqualTo("中国");
            //执行查询
            List<Country> countryList = countryMapper.selectByExample(example);
            printCountryList(countryList);
        } finally {
    
    
            //不妥忘记关闭 sqlSession
            sqlSession.close();
        }
    }
}

BaseMapperTest:

package cn.linst;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;

import java.io.IOException;
import java.io.Reader;



public class BaseMapperTest {
    
    

    private static SqlSessionFactory sqlSessionFactory;

    @BeforeClass
    public static void init () {
    
    
        try {
    
    
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (IOException ex) {
    
    
            ex.printStackTrace();
        }
    }

    public SqlSession getSqlSession() {
    
    
        return sqlSessionFactory.openSession();
    }
}

运行测试结果:

3     xx3  x3
2     xx2  x2
1     xx1  x1

猜你喜欢

转载自blog.csdn.net/tongwudi5093/article/details/114604486