Mybatis不启动项目直接测试Mapper的实现方法

 更新时间:2024年09月19日 09:54:09   作者:豆腐脑lr  
在项目开发中,测试单个Mybatis Mapper方法通常需要启动整个SpringBoot项目,消耗大量时间,本文介绍通过Main方法和Mybatis配置类,快速测试Mapper功能,无需启动整个项目,这方法使用AnnotationConfigApplicationContext容器

前言

在项目开发过程中,有时候一个庞大的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也无法正常工作。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 如何在pom文件中引入本地jar包并打包

    如何在pom文件中引入本地jar包并打包

    在项目中使用本地JAR文件的方法有很多,下面这篇文章主要给大家介绍了关于如何在pom文件中引入本地jar包并打包的相关资料,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2023-06-06
  • Mybatis RowBounds 限制查询条数的实现代码

    Mybatis RowBounds 限制查询条数的实现代码

    Oracle 数据库查询增加RowBounds限制查询条数,默认是0到1000条。下面给大家分享Mybatis RowBounds 限制查询条数的实现代码,需要的朋友参考下吧
    2016-11-11
  • Spring Boot项目获取resources目录下文件并返回给前端的方案

    Spring Boot项目获取resources目录下文件并返回给前端的方案

    我们在项目中经常碰到需要读取固定文件的场景,如模板文件,一般做法是将文件放在resources目录下,程序通过多种方式可以顺利读取文件,这篇文章主要给大家介绍了关于Spring Boot项目获取resources目录下文件并返回给前端的相关资料,需要的朋友可以参考下
    2024-07-07
  • 使用 Java 开发 Gradle 插件的步骤

    使用 Java 开发 Gradle 插件的步骤

    这篇文章主要介绍了使用 Java 开发 Gradle 插件的步骤,帮助大家更好的理解和学习使用Java,感兴趣的朋友可以了解下
    2021-03-03
  • Dapr在Java中的服务调用实战过程详解

    Dapr在Java中的服务调用实战过程详解

    这篇文章主要为大家介绍了Dapr在Java中的服务调用实战过程详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06
  • Java中的5种同步辅助类介绍

    Java中的5种同步辅助类介绍

    你提交了一些任务,但你想等它们都完成了再做另外一些事情;你提交了一些任务,但是不想让它们立刻执行,等你喊123开始的时候,它们才开始执行;等等这些场景,线程之间需要相互配合,或者等待某一个条件成熟执行。这些场景想你就需要用到同步辅助类
    2014-04-04
  • SWT(JFace)Group(分组显示)

    SWT(JFace)Group(分组显示)

    SWT(JFace)体验之Group(分组显示)
    2009-06-06
  • 实例讲解Java中的synchronized

    实例讲解Java中的synchronized

    这篇文章主要介绍了Java中synchronized的使用方法,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-07-07
  • JavaScript base64 与 File 之间的互转(操作方法)

    JavaScript base64 与 File 之间的互转(操作方法)

    在JavaScript 中,可以使用 Blob 对象将 base64 字符串转换为 File 对象,这篇文章主要介绍了JavaScript base64 与 File之间的互转,需要的朋友可以参考下
    2024-05-05
  • Java 将字符串动态生成字节码的实现方法

    Java 将字符串动态生成字节码的实现方法

    本篇文章主要是对Java将字符串动态生成字节码的实现方法进行了介绍,需要的朋友可以过来参考下,希望对大家有所帮助
    2014-01-01

最新评论