欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Mybatis不啟動項目直接測試Mapper的實現(xiàn)方法

 更新時間:2024年09月19日 09:54:09   作者:豆腐腦lr  
在項目開發(fā)中,測試單個Mybatis Mapper方法通常需要啟動整個SpringBoot項目,消耗大量時間,本文介紹通過Main方法和Mybatis配置類,快速測試Mapper功能,無需啟動整個項目,這方法使用AnnotationConfigApplicationContext容器

前言

在項目開發(fā)過程中,有時候一個龐大的SpringBoot 項目的啟動時間可能要幾分鐘的時間,這時候我們?nèi)绻霚y試自己寫的某個mybatis的Mapper的方法,要浪費大量時間在等待項目啟動上。

本文通過一個Main方法和一個Mybatis配置類實現(xiàn)無需啟動項目直接測試Mapper功能。

本文的工程目錄結(jié)構(gòu)如下:

1. 依賴

由于現(xiàn)在很多項目都是直接用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. 數(shù)據(jù)庫

數(shù)據(jù)庫建表語句:

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;

數(shù)據(jù)庫中數(shù)據(jù):

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;

    /**
     * 分?jǐn)?shù)
     */
    @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);

}

對應(yīng)的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,因此容器的啟動速度非??臁?/p>

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配置類實現(xiàn)無需啟動項目直接測試Mapper功能。

雖然我們沒有啟動項目,但是實際上還是啟動了一個SpringBoot容器,只是這個容器內(nèi)的Bean非常少,所以啟動速度非???。

當(dāng)然這個容器也是必須要有的,不然Mybatis也無法正常工作。

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

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

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

    在項目中使用本地JAR文件的方法有很多,下面這篇文章主要給大家介紹了關(guān)于如何在pom文件中引入本地jar包并打包的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2023-06-06
  • Mybatis RowBounds 限制查詢條數(shù)的實現(xiàn)代碼

    Mybatis RowBounds 限制查詢條數(shù)的實現(xiàn)代碼

    Oracle 數(shù)據(jù)庫查詢增加RowBounds限制查詢條數(shù),默認(rèn)是0到1000條。下面給大家分享Mybatis RowBounds 限制查詢條數(shù)的實現(xiàn)代碼,需要的朋友參考下吧
    2016-11-11
  • Spring?Boot項目獲取resources目錄下文件并返回給前端的方案

    Spring?Boot項目獲取resources目錄下文件并返回給前端的方案

    我們在項目中經(jīng)常碰到需要讀取固定文件的場景,如模板文件,一般做法是將文件放在resources目錄下,程序通過多種方式可以順利讀取文件,這篇文章主要給大家介紹了關(guān)于Spring?Boot項目獲取resources目錄下文件并返回給前端的相關(guān)資料,需要的朋友可以參考下
    2024-07-07
  • 使用 Java 開發(fā) Gradle 插件的步驟

    使用 Java 開發(fā) Gradle 插件的步驟

    這篇文章主要介紹了使用 Java 開發(fā) Gradle 插件的步驟,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下
    2021-03-03
  • Dapr在Java中的服務(wù)調(diào)用實戰(zhàn)過程詳解

    Dapr在Java中的服務(wù)調(diào)用實戰(zhàn)過程詳解

    這篇文章主要為大家介紹了Dapr在Java中的服務(wù)調(diào)用實戰(zhàn)過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-06-06
  • Java中的5種同步輔助類介紹

    Java中的5種同步輔助類介紹

    你提交了一些任務(wù),但你想等它們都完成了再做另外一些事情;你提交了一些任務(wù),但是不想讓它們立刻執(zhí)行,等你喊123開始的時候,它們才開始執(zhí)行;等等這些場景,線程之間需要相互配合,或者等待某一個條件成熟執(zhí)行。這些場景想你就需要用到同步輔助類
    2014-04-04
  • SWT(JFace)Group(分組顯示)

    SWT(JFace)Group(分組顯示)

    SWT(JFace)體驗之Group(分組顯示)
    2009-06-06
  • 實例講解Java中的synchronized

    實例講解Java中的synchronized

    這篇文章主要介紹了Java中synchronized的使用方法,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • JavaScript base64 與 File 之間的互轉(zhuǎn)(操作方法)

    JavaScript base64 與 File 之間的互轉(zhuǎn)(操作方法)

    在JavaScript 中,可以使用 Blob 對象將 base64 字符串轉(zhuǎn)換為 File 對象,這篇文章主要介紹了JavaScript base64 與 File之間的互轉(zhuǎn),需要的朋友可以參考下
    2024-05-05
  • Java 將字符串動態(tài)生成字節(jié)碼的實現(xiàn)方法

    Java 將字符串動態(tài)生成字節(jié)碼的實現(xiàn)方法

    本篇文章主要是對Java將字符串動態(tài)生成字節(jié)碼的實現(xiàn)方法進(jìn)行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助
    2014-01-01

最新評論