⭐⭐⭐ Spring Boot 项目实战 ⭐⭐⭐ Spring Cloud 项目实战
《Dubbo 实现原理与源码解析 —— 精品合集》 《Netty 实现原理与源码解析 —— 精品合集》
《Spring 实现原理与源码解析 —— 精品合集》 《MyBatis 实现原理与源码解析 —— 精品合集》
《Spring MVC 实现原理与源码解析 —— 精品合集》 《数据库实体设计合集》
《Spring Boot 实现原理与源码解析 —— 精品合集》 《Java 面试题 + Java 学习指南》

摘要: 原创出处 juejin.cn/post/7271942371638214708 「葛俊」欢迎转载,保留摘要,谢谢!


🙂🙂🙂关注微信公众号:【芋道源码】有福利:

  1. RocketMQ / MyCAT / Sharding-JDBC 所有源码分析文章列表
  2. RocketMQ / MyCAT / Sharding-JDBC 中文注释源码 GitHub 地址
  3. 您对于源码的疑问每条留言都将得到认真回复。甚至不知道如何读源码也可以请教噢。
  4. 新的源码解析文章实时收到通知。每周更新一篇左右。
  5. 认真的源码交流微信群。

快速测试mybatis的sql

当我们写完sql后,我们需要测试下sql是否符合预期,在填入各种参数后能否正常工作,尤其是对于复杂的sql。

一般我们测试可能是如下的代码:

由于需要启动spring,当项目较大的时候启动速度很慢,有些项目的启动时间超过30秒。导致测试sql速度很慢,尤其项目上不允许引入热部署jrebel,改下sql重新再测试等很花时间。

如果只是单独测试sql是否正确,没必要启动spring容器,mybatis可以直接定义配置文件进行启动,测试代码如下

配置文件

这样我们可以直接测试mybatis的sql而不需要启动spring

速度非常快 如下:

基本上1,2秒钟就跑完了。相比启动spring的测试效率提升很高。

生成testcase支持PageHelper分页插件

修改setUp方法加入interceptor即可

SqlSessionFactory builder = new SqlSessionFactoryBuilder().build(UserMapperTest.class.getClassLoader().getResourceAsStream("mybatisTestConfiguration/UserMapperTestConfiguration.xml"));
//you can use builder.openSession(false) to not commit to database
PageInterceptor interceptor = new PageInterceptor();
builder.getConfiguration().addInterceptor(interceptor);
mapper = builder.getConfiguration().getMapper(UserMapper.class, builder.openSession(true));

生成testcase支持mybatisplus

在生成的testcase中有一个setUp方法,将SqlSessionFactoryBuilder改成MybatisSqlSessionFactoryBuilder即可测试mybatisplus自带的一些方法

mybatisplus添加分页插件和乐观锁插件

在test类可以修改setUpMybatisDatabase 如下

@org.junit.BeforeClass
public static void setUpMybatisDatabase() {
SqlSessionFactory builder = new MybatisSqlSessionFactoryBuilder().build(SymphonyClientMapperTest.class.getClassLoader().
getResourceAsStream("mybatisTestConfiguration/SymphonyClientMapperTestConfiguration.xml"));
final MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
builder.getConfiguration().addInterceptor(interceptor);
//you can use builder.openSession(false) to not commit to database
mapper = builder.getConfiguration().getMapper(SymphonyClientMapper.class, builder.openSession(true));
}

这样就可以快速测试mybatis的sql了.

也可以试试我写的Intellij下的MybatisCodeHelperPro插件,链接:

❝

https://plugins.jetbrains.com/plugin/9837-mybatiscodehelperpro

❞

插件可以自动生成测试的java类和配置文件,不需要手动去配置。

文章目录
  1. 1. 快速测试mybatis的sql
  2. 2. 生成testcase支持PageHelper分页插件
  3. 3. 生成testcase支持mybatisplus
  4. 4. mybatisplus添加分页插件和乐观锁插件