SpringBoot与MyBatis零XML配置集成和集成测试

这篇具有很好参考价值的文章主要介绍了SpringBoot与MyBatis零XML配置集成和集成测试。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

原文地址:https://ntopic.cn/p/2023070801/

源代码先行:

  • Gitee本文介绍的完整仓库:https://gitee.com/obullxl/ntopic-boot
  • GitHub本文介绍的完整仓库:https://github.com/obullxl/ntopic-boot

背景介绍

在Java众多的ORM框架里面,MyBatis是比较轻量级框架之一,既有数据表和Java对象映射功能,在SQL编写方面又不失原生SQL的特性。SpringBoot提倡使用注解代替XML配置,同样的,在集成MyBatis时也可以做到全注解化,无XML配置。相关的集成方法网上存在大量的教程,本文是个人在实际项目过程的一个备忘,并不是复制和粘贴,同时在本文后面提供了完整的集成测试用例。

MyBatis集成

涉及到以下4个方面:

  • 我们Maven工程是一个SpringBoot工程
  • 引入MyBatis的Starter依赖
  • SpringBoot工程配置中增加MyBatis的配置
  • Mapper/DAO通过注解实现

SpringBoot工程依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/>
    </parent>

  <!-- 其他部分省略 -->
</project>

MyBatis Starter依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <!-- 其他省略 -->
      <dependencyManagement>
        <dependencies>
          <!-- MyBatis -->
          <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.2.0</version>
            </dependency>

          <!-- MySQL -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.26</version>
            </dependency>

          <!-- SQLite -->
            <dependency>
                <groupId>org.xerial</groupId>
                <artifactId>sqlite-jdbc</artifactId>
                <version>3.39.2.0</version>
                <scope>provided</scope>
            </dependency>

            <!-- Druid -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.2</version>
            </dependency>
          
          <!-- 其他省略 -->
          
        </dependencies>
      </dependencyManagement>
  <!-- 其他省略 -->
</project>

SpringBoot Main配置

  • application.properties配置,增加DB数据源:
#
# 数据库:url值设置成自己的文件路径
#
ntopic.datasource.driver-class-name=org.sqlite.JDBC
ntopic.datasource.url=jdbc:sqlite:./../NTopicBoot.sqlite
ntopic.datasource.userName=
ntopic.datasource.password=
  • MapperScan注解:指明MyBatis的Mapper在哪写包中,cn.ntopic.das..**.dao指明,我们的Mapper类所在的包
/**
 * Author: obullxl@163.com
 * Copyright (c) 2020-2021 All Rights Reserved.
 */
package cn.ntopic;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.Configuration;
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.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

/**
 * NTopic启动器
 *
 * @author obullxl 2021年06月05日: 新增
 */
@SpringBootApplication
@MapperScan(basePackages = "cn.ntopic.das..**.dao", sqlSessionFactoryRef = "ntSqlSessionFactory")
public class NTBootApplication {

    /**
     * SpringBoot启动
     */
    public static void main(String[] args) {
        SpringApplication.run(NTBootApplication.class, args);
    }

    /**
     * DataSource配置
     */
    @Bean(name = "ntDataSource", initMethod = "init", destroyMethod = "close")
    public DruidDataSource ntDataSource(@Value("${ntopic.datasource.url}") String url
            , @Value("${ntopic.datasource.userName}") String userName
            , @Value("${ntopic.datasource.password}") String password) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);

        dataSource.setInitialSize(0);
        dataSource.setMinIdle(1);
        dataSource.setMaxActive(5);
        dataSource.setMaxWait(3000L);

        return dataSource;
    }

    /**
     * MyBatis事务配置
     */
    @Bean("ntSqlSessionFactory")
    public SqlSessionFactoryBean ntSqlSessionFactory(@Qualifier("ntDataSource") DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        Configuration configuration = new Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(configuration);

        return sqlSessionFactoryBean;
    }

    /** 其他代码省略 */
}

MyBatis Mapper类/DAO类

几个核心的注解:文章来源地址https://www.toymoban.com/news/detail-533498.html

  • Insert插入
  • Select查询
  • Update更新
  • Delete删除
/**
 * Author: obullxl@163.com
 * Copyright (c) 2020-2021 All Rights Reserved.
 */
package cn.ntopic.das.dao;

import cn.ntopic.das.model.UserBaseDO;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

/**
 * @author obullxl 2021年10月17日: 新增
 */
@Repository("userBaseDAO")
public interface UserBaseDAO {

    /**
     * 新增用户记录
     */
    @Insert("INSERT INTO nt_user_base (id, name, password, role_list, ext_map, create_time, modify_time)" +
            " VALUES (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{roleList,jdbcType=VARCHAR}, #{extMap,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{modifyTime,jdbcType=TIMESTAMP})")
    void insert(UserBaseDO userBaseDO);

    /**
     * 根据ID查询记录
     */
    @Select("SELECT * FROM nt_user_base WHERE id = #{id,jdbcType=VARCHAR}")
    UserBaseDO selectById(@Param("id") String id);

    /**
     * 根据名称查询记录
     */
    @Select("SELECT * FROM nt_user_base WHERE name = #{name,jdbcType=VARCHAR}")
    UserBaseDO selectByName(@Param("name") String name);

    /**
     * 查询所有用户
     */
    @Select("SELECT * FROM nt_user_base LIMIT 30")
    List<UserBaseDO> select();

    /**
     * 更新角色列表
     * FIXME: SQLite/MySQL 当前时间函数不一致,本次通过入参传入!
     */
    @Update("UPDATE nt_user_base SET modify_time=#{modifyTime,jdbcType=TIMESTAMP}, role_list=#{roleList,jdbcType=VARCHAR} WHERE id=#{id,jdbcType=VARCHAR}")
    int updateRoleList(@Param("id") String id, @Param("modifyTime") Date modifyTime, @Param("roleList") String roleList);

    /**
     * 删除用户记录
     */
    @Delete("DELETE FROM nt_user_base WHERE id = #{id,jdbcType=VARCHAR}")
    int deleteById(@Param("id") String id);

    /**
     * 删除用户记录
     */
    @Delete("DELETE FROM nt_user_base WHERE name = #{name,jdbcType=VARCHAR}")
    int deleteByName(@Param("name") String name);

}

集成测试(包括CRUD操作)

/**
 * Author: obullxl@163.com
 * Copyright (c) 2020-2021 All Rights Reserved.
 */
package cn.ntopic.das.dao;

import cn.ntopic.das.model.UserBaseDO;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;

/**
 * @author obullxl 2021年10月17日: 新增
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserBaseDAOTest extends AbstractJUnit4SpringContextTests {

    @Autowired
    @Qualifier("userBaseDAO")
    private UserBaseDAO userBaseDAO;

    /**
     * CRUD简单测试
     */
    @Test
    public void test_insert_select_update_delete() {
        final String id = "ID-" + RandomUtils.nextLong();
        final String name = "NAME-" + RandomUtils.nextLong();

        // 1. 清理数据
        this.userBaseDAO.deleteById(id);
        this.userBaseDAO.deleteByName(name);

        // 请求数据 - 验证
        UserBaseDO userBaseDO = this.userBaseDAO.selectById(id);
        Assert.assertNull(userBaseDO);

        userBaseDO = this.userBaseDAO.selectByName(name);
        Assert.assertNull(userBaseDO);

        try {
            // 2. 新增数据
            UserBaseDO newUserDO = new UserBaseDO();
            newUserDO.setId(id);
            newUserDO.setName(name);
            newUserDO.setCreateTime(new Date());
            newUserDO.setModifyTime(new Date());
            this.userBaseDAO.insert(newUserDO);

            // 3. 数据查询 - 新增验证
            UserBaseDO checkUserDO = this.userBaseDAO.selectById(id);
            Assert.assertNotNull(checkUserDO);
            Assert.assertEquals(name, checkUserDO.getName());
            Assert.assertNotNull(checkUserDO.getCreateTime());
            Assert.assertNotNull(checkUserDO.getModifyTime());
            Assert.assertTrue(StringUtils.isBlank(checkUserDO.getRoleList()));

            // 4. 更新数据
            int update = this.userBaseDAO.updateRoleList(id, new Date(), "ADMIN,DATA");
            Assert.assertEquals(1, update);

            // 更新数据 - 验证
            checkUserDO = this.userBaseDAO.selectById(id);
            Assert.assertNotNull(checkUserDO);
            Assert.assertEquals("ADMIN,DATA", checkUserDO.getRoleList());

            // 5. 数据删除
            int delete = this.userBaseDAO.deleteById(id);
            Assert.assertEquals(1, delete);

            delete = this.userBaseDAO.deleteByName(name);
            Assert.assertEquals(0, delete);
        } finally {
            // 清理数据
            this.userBaseDAO.deleteById(id);
        }
    }
}

到了这里,关于SpringBoot与MyBatis零XML配置集成和集成测试的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【六】SpringBoot集成MyBatis-yml自动化配置原理详解

            简介:spring boot整合mybatis开发web系统目前来说是市面上主流的框架,每个Java程序和springboot mybatis相处的时间可谓是比和自己女朋友相处的时间都多,但是springboot mybatis并没有得到你的真爱,因为你只是为了养活你女朋友而委曲求全的和spring boot mybatis假意相处。和

    2024年02月10日
    浏览(42)
  • (MVC)SpringBoot+Mybatis+Mapper.xml

    前言:本篇博客主要对MVC架构、Mybatis工程加深下理解,前面写过一篇博客:SprintBoot+html/css/js+mybatis的demo,里面涉及到了Mybatis的应用,此篇博客主要介绍一种将sql语句写到了配置文件里的方法,即Mybatis里Mapper.xml文件配置,其主要用于定义sql语句和映射关系 目录 MVC架构流程图

    2024年02月13日
    浏览(31)
  • MyBatis基本使用及XML配置

    MyBatis是一款优秀的 持久层框架, 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程,减少了代码的冗余,减少程序员的操作,可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 实体类 【Plain Old Java Objects,普通的 Java对象】映射成数据库中的

    2024年02月03日
    浏览(69)
  • Mybatis—XML配置文件、动态SQL

    学习完Mybatis的基本操作之后,继续学习Mybatis—XML配置文件、动态SQL。 Mybatis的开发有两种方式: 注解 XML 之前学习的基本操作都是基于注解开发。使用Mybatis的注解方式,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能,建议使用XML来配置映射语句,也就

    2024年02月06日
    浏览(29)
  • Mybatis|mapper配置文件xml位置

    在核心配置文件mybatis-config.xml中设置映射文件位置 application.yml文件中添加配置: mybatis案例中和springboot中都是一样的,只要目录名和包名相同 需要在pom.xml中添加如下内容 越努力,越幸运! codefishyyf与你一起努力!

    2024年02月06日
    浏览(54)
  • MyBatis-config.xml配置文件

            mybatis的核心配置文件(mybatis-config.xml),比如配置jdbc连接信息,注册mapper等等,我们需要对这个配置文件有详细的了解。 官网地址有详细介绍 mybatis – MyBatis 3 | 配置         在通常的情况下,我们会将jdbc的配置信息,写在一个外部文件,然后引入到mybatis-co

    2024年02月03日
    浏览(31)
  • springboot+maven插件调用mybatis generator自动生成对应的mybatis.xml文件和java类

    mybatis最繁琐的事就是sql语句和实体类,sql语句写在java文件里很难看,字段多的表一开始写感觉阻力很大,没有耐心,自动生成便成了最称心的做法。自动生成xml文件,dao接口,实体类,虽一直感觉不太优雅,但省去了很多麻烦,当表增加或修改字段的时候重新生成便轻松搞

    2024年02月14日
    浏览(32)
  • SpringBoot 集成 Mybatis

    (只有操作,没有理论,仅供参考学习) 1.1 数据库版本: 1.2 启动 mysql 服务: 1.3 新创建数据库 spring,并创建一个 user 表,user 表详情: 如下图: 2.1 使用 spring 官网页面创建工程(其他亦可),链接:Spring Initializr 创建 SpringBoot 工程,如下图: 2.2 用 IDEA 打开工程: 2.3 配置

    2024年02月16日
    浏览(39)
  • 1. Springboot集成Mybatis

    在深入理解mybatis源码之前,首先搭建mybatis的测试环境用于跟踪代码测试用。 下面介绍两种springboot集成mybatis运行环境的案例。一种是通过springboot包装mybatis的构建过程,一种是自行构建Mybatis的执行环境。 以查询user表为例,数据如下 1.1 创建表对应的bean 1.2 创建查询接口dao

    2023年04月19日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包