纯代码测试mybatis的xml语句,无需修改mybatis配置文件

背景:有时候需要测试xml中的sql写的对不对,重启整个系统比较慢。

一般的方式是:

  (1)创建mybatis-config.xml,里面配置datasource,然后配置要测试的sql所在xml

 (2)然后再通过mybatis自带的方式获取它的SqlSessionFactory 和sqlSession 


import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MybatisTest {
     @Before
    public void beforeTest() throws IOException {
        System.out.println("-------------------------------before----------------------------");
        // 创建数据源
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession(true);
    }
    @After
    public void after(){
        System.out.println("-------------------------------after----------------------------");
        sqlSession.close();
    }
     @Test
    public void testMybatis() throws IOException {
         UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String,Object> params = new HashMap<>();
         params.put("XX",1001);
        System.out.println(mapper.query(params));
    }
}

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- 打印查询语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!-- 自动驼峰 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="org.postgresql.Driver"/>
                <property name="url" value="jdbc:postgresql://1xxxxxxxxxxxxxxxx"/>
                <property name="username" value="xx"/>
                <property name="password" value="xxxx"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        
        <mapper resource="mappers/comxxxxx/UserMapper.xml"/>

    </mappers>

</configuration>

其实也挺方便的,但还是很烦,每次要去mybatis-config.xml里面去加 xml!!!

借鉴springboot中对mapperLocations的处理:

改进后的方法:

package com.test;

import com.spring.mybatis.mapper.DeptMapperAnnotationSpring;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.*;

public class MybatisTest {
    SqlSession sqlSession;
    DataSource dataSource;

    private void setDataSource(){
        // 创建数据源
        dataSource = new PooledDataSource("oracle.jdbc.driver.OracleDriver",
                "jdbc:oracle:thin:@//127.0.0.1/orcl",
                "scott",
                "xx");
    }

    public Resource[] resolveMapperLocations(String[] mapperLocations) {
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        List<Resource> resources = new ArrayList<Resource>();
        if (mapperLocations != null) {
            for (String mapperLocation : mapperLocations) {
                try {
                    Resource[] mappers = resourceResolver.getResources(mapperLocation);
                    resources.addAll(Arrays.asList(mappers));
                } catch (IOException e) {
                    // ignore
                }
            }
        }
        return resources.toArray(new Resource[resources.size()]);
    }

    @Before
    public void beforeTestSpring() throws Exception {
        System.out.println("-------------------------------before222----------------------------");
        // 创建数据源
        setDataSource();
        SqlSessionFactoryBean sqlSessionFactoryBean  = new SqlSessionFactoryBean();
        org.springframework.core.io.Resource[]   resources = resolveMapperLocations(new String[]{"mapper/*.xml"});
        sqlSessionFactoryBean.setMapperLocations(resources);
        sqlSessionFactoryBean.setDataSource(dataSource);
        SqlSessionFactory sqlSessionFactory =   sqlSessionFactoryBean.getObject();
        sqlSession =  sqlSessionFactory.openSession(true);

    }
    @After
    public void after(){
        System.out.println("----------after-------------");
        sqlSession.close();
    }

    @Test
    public void testMybatis() throws IOException {
        DeptMapperAnnotationSpring mapper = sqlSession.getMapper(DeptMapperAnnotationSpring.class);
        Map<String,Object> params = new HashMap<>();
        params.put("XX",1001);
        System.out.println(mapper.queryDept(params));
    }

}

这样的好处就是:

(1)配一个mapperLocation就好了,不用再去一个个配sql的xml位置。

(2)springboot单元测试也可以做测试,但是会启动所有的bean,扫描所有xml,这样不用依赖spring启动,只要有spring环境即可,同时又避免了springboot整个启动,扫描所有xml。

Guess you like

Origin blog.csdn.net/x18094/article/details/120494419