Mybatis不启动项目直接测试Mapper的实现方法
作者:豆腐脑lr
前言
在项目开发过程中,有时候一个庞大的SpringBoot 项目的启动时间可能要几分钟的时间,这时候我们如果想测试自己写的某个mybatis的Mapper的方法,要浪费大量时间在等待项目启动上。
本文通过一个Main方法和一个Mybatis配置类实现无需启动项目直接测试Mapper功能。
本文的工程目录结构如下:
1. 依赖
由于现在很多项目都是直接用mybatis-plus,所以本文依赖也是直接选用了mybatis-plus。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.3.2</version> <dependency>
2. 数据库
数据库建表语句:
CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `score` int(11) NOT NULL, `age` int(5) NOT NULL, `gender` int(4) NOT NULL, `oms_order_no` varchar(255) NOT NULL COMMENT 'oms单号', `warehouse_code` varchar(64) NOT NULL COMMENT '仓库编码', PRIMARY KEY (`id`), UNIQUE KEY `idx_unique_oms_order_warehouse_code` (`oms_order_no`,`warehouse_code`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
数据库中数据:
3. 实体类
package com.whut.mybatis.domain; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @TableName(value = "student") public class Student { /** * id */ @TableId(value = "id",type = IdType.AUTO) private Integer id; /** * 名字 */ @TableField("name") private String name; /** * 分数 */ @TableField("score") private Integer score; /** * 年龄 */ @TableField("age") private Integer age; /** * 性别 */ @TableField("gender") private Integer gender; /** * oms单号 */ @TableField("oms_order_no") private String omsOrderNo; /** * 仓库号 */ @TableField("warehouse_code") private String warehouseCode; }
4. Mapper文件
mapper接口:
public interface StudentMapper extends BaseMapper<Student> { @Select("select age from student") List<Integer> getAllage(); Student findByName(@Param("name") String name); }
对应的xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.whut.mybatis.mapper.StudentMapper"> <select id="findByName" resultType="com.whut.mybatis.domain.Student"> select * from student where name=#{name} limit 1 </select> </mapper>
5. 配置类
package com.whut.mybatis.config; import com.baomidou.mybatisplus.core.MybatisConfiguration; import org.apache.ibatis.logging.stdout.StdOutImpl; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import javax.sql.DataSource; @Configuration @MapperScan(basePackages = "com.whut.mybatis.mapper") public class TestMybatisConfig { @Bean(name = "testDataSource") public DataSource dbDataSource() { DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(); driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver"); driverManagerDataSource.setPassword("whut123456"); driverManagerDataSource.setUsername("root"); driverManagerDataSource.setUrl("jdbc:mysql://123.60.223.167:3306/mybatis?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"); return driverManagerDataSource; } @Bean(name = "testSqlSessionFactory") public SqlSessionFactory dbSqlSessionFactory(@Qualifier("testDataSource") DataSource dataSource, @Value("classpath*:mapper/*Mapper.xml") Resource[] mapperLocations) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(mapperLocations); //https://blog.csdn.net/weixin_41785851/article/details/119739897 MybatisConfiguration configuration = new MybatisConfiguration(); configuration.setMapUnderscoreToCamelCase(true); // 配置打印sql语句 configuration.setLogImpl(StdOutImpl.class); bean.setConfiguration(configuration); return bean.getObject(); } @Bean(name = "testTransactionManager") public DataSourceTransactionManager dbTransactionManager(@Qualifier("testDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } }
6. Main方法
这个Main方法的原理是是使用了一种注解方式的SpringBoot容器AnnotationConfigApplicationContext
,这个容器里面只存放了配置BeanTestMybatisConfig
,因此容器的启动速度非常快。
package com.whut.mybatis; import com.whut.mybatis.config.TestMybatisConfig; import com.whut.mybatis.domain.Student; import com.whut.mybatis.mapper.StudentMapper; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * Hello world! * */ public class App { public static void main( String[] args ) { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(TestMybatisConfig.class); Student student = ac.getBean(StudentMapper.class).findByName("111"); System.out.println(student); } }
启动后控制台打印如下:
JDBC Connection [com.mysql.jdbc.JDBC4Connection@33f676f6] will not be managed by Spring
==> Preparing: select * from student where name=? limit 1
==> Parameters: 111(String)
<== Columns: id, name, score, age, gender, oms_order_no, warehouse_code
<== Row: 3, 111, 100, 25, 1, 5416161, 4841851515
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6e535154]
Student(id=3, name=111, score=100, age=25, gender=1, omsOrderNo=5416161, warehouseCode=4841851515)
综上所述,本文通过一个Main方法和一个Mybatis配置类实现无需启动项目直接测试Mapper功能。
虽然我们没有启动项目,但是实际上还是启动了一个SpringBoot容器,只是这个容器内的Bean非常少,所以启动速度非常快。
当然这个容器也是必须要有的,不然Mybatis也无法正常工作。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。