SpringBoot与MyBatis零XML配置集成(附源码)

源代码先行:

  • 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类

几个核心的注解:

  • 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);
        }
    }
}

关注本公众号,我们共同学习进步 👇🏻👇🏻👇🏻

微信公众号:老牛同学


我的本博客原地址:https://mp.weixin.qq.com/s/JpvF9PfihYDZffPRKMDWwg


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/672669.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【JavaEE进阶】——MyBatis操作数据库 (#{}与${} 以及 动态SQL)

目录 &#x1f6a9;#{}和${} &#x1f388;#{} 和 ${}区别 &#x1f388;${}使用场景 &#x1f4dd;排序功能 &#x1f4dd;like 查询 &#x1f6a9;数据库连接池 &#x1f388;数据库连接池使⽤ &#x1f6a9;MySQL开发企业规范 &#x1f6a9;动态sql &#x1f388…

PCIe总线-事物层之TLP路由介绍(七)

1.概述 下图是一个PCIe总线系统示意图。此时RC发出一个TLP&#xff0c;经过Switch访问EP&#xff0c;TLP的路径为红色箭头所示。首先TLP从RC的下行OUT端口发出&#xff0c;Switch的上行IN端口接收到该TLP后&#xff0c;根据其路由信息&#xff0c;将其转发到Switch的下行OUT端…

Vue.js 动态组件与异步组件

title: Vue.js 动态组件与异步组件 date: 2024/6/2 下午9:08:50 updated: 2024/6/2 下午9:08:50 categories: 前端开发 tags:Vue概览动态组件异步加载性能提升路由管理状态控制工具生态 第1章 Vue.js 简介 1.1 Vue.js 概述 Vue.js 是一个渐进式的JavaScript框架&#xff0c;…

docker以挂载目录启动容器报错问题的解决

拉取镜像&#xff1a; docker pull elasticsearch:7.4.2 docker pull kibana:7.4.2 创建实例&#xff1a; mkdir -p /mydata/elasticsearch/configmkdir -p /mydata/elasticsearch/dataecho "http.host: 0.0.0.0" >> /mydata/elasticsearch/config/elasti…

深入解析Java中List和Map的多层嵌套与拆分

深入解析Java中List和Map的多层嵌套与拆分 深入解析Java中List和Map的多层嵌套与拆分技巧 &#x1f4dd;摘要引言正文内容什么是嵌套数据结构&#xff1f;例子&#xff1a; 遍历嵌套List和Map遍历嵌套List遍历嵌套Map 拆分嵌套数据结构拆分嵌套List拆分嵌套Map &#x1f914; Q…

【CTF Web】CTFShow web18 Writeup(文件包含漏洞+日志注入+RCE)

web18 1 阿呆加入了过滤&#xff0c;这下完美了。 解法 <?php if(isset($_GET[c])){$c$_GET[c];if(!preg_match("/php|file/i",$c)){include($c);}}else{highlight_file(__FILE__); } ?>用 dirsearch 扫了下&#xff0c;什么都没找到。 Wappalyzer 检测到 …

计算机视觉与模式识别实验1-3 图像滤波

文章目录 &#x1f9e1;&#x1f9e1;实验流程&#x1f9e1;&#x1f9e1;1. 对图像加入椒盐噪声&#xff0c;并用均值滤波进行过滤2.对图像加入高斯噪声&#xff0c;并用高斯滤波进行过滤3.对图像加入任意噪声&#xff0c;并用中值滤波进行过滤4.读入一张灰度图像&#xff0c;…

Java项目:95 springboot班级回忆录的设计与实现

作者主页&#xff1a;舒克日记 简介&#xff1a;Java领域优质创作者、Java项目、学习资料、技术互助 文中获取源码 项目介绍 本管理系统有管理员和用户。 本海滨学院班级回忆录管理员功能有个人中心&#xff0c;用户信息管理&#xff0c;班委信息管理&#xff0c;班级信息管理…

云计算-高级云资源配置(Advanced Cloud Provisioning)

向Bucket添加公共访问&#xff08;Adding Public Access to Bucket&#xff09; 在模块5中&#xff0c;我们已经看到如何使用CloudFormation创建和更新一个Bucket。现在我们将进一步更新该Bucket&#xff0c;添加公共访问权限。我们在模块5中使用的模板&#xff08;third_templ…

多维数组找最大值

调用JavaScript的一个内置函数&#xff1a;Math.max() <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title…

汇编原理(二)寄存器——CPU工作原理

寄存器&#xff1a;所有寄存器都是16位&#xff08;0-15&#xff09;&#xff0c;可以存放两个字节 AX,BX,CX,DX存放一般性数据&#xff0c;称为通用寄存器 AX的逻辑结构。最大存放的数据为2的16次方减1。可分为AH和AL&#xff0c;兼容8位寄存器。 字&#xff1a;1word 2Byte…

c++实现:小型公司的信息管理系统(关于多态)

前言&#xff1a; 介绍员工信息&#xff1a;一个小型公司的人员信息管理系统 某小型公司&#xff0c;主要有四类人员&#xff1a;经理、技术人员、销售经理和推销员。现在&#xff0c;需要存储这些人员的姓名、编号、级别、当前薪水。计算月薪总额并显示全部信息人员编号基数为…

前端组件业务数据选择功能优雅写法

1. 业务场景 后台管理在实际业务中&#xff0c;经常可见的功能为&#xff1a;在当前的页面中从其他列表中选择数据。 例如&#xff0c;在一个商品活动列表页面中 需要选择配置的商品。 2. 遇到问题 从代码划分的角度来说&#xff0c;每个业务列表代码首先分散开来&#xff0…

基于Weaviate构建多模态检索和多模态检索增强(RAG): Building Multimodal Search and RAG

Building Multimodal Search and RAG 本文是学习 https://www.deeplearning.ai/short-courses/building-multimodal-search-and-rag/ 这门课的学习笔记。 What you’ll learn in this course Learn how to build multimodal search and RAG systems. RAG systems enhance an …

张大哥笔记:下一个风口是什么?

我们经常会问&#xff0c;下一个风口是什么&#xff1f;我们可以大胆预测一下&#xff0c;2024年的风口是什么呢&#xff1f; 40年前&#xff0c;如果你会开车&#xff0c;那就是响当当的铁饭碗&#xff1b; 30年前&#xff0c;如果你会英语和电脑&#xff0c;那也绝对是个人才…

SSMP整合案例第五步 在前端页面上拿到service层调数据库里的数据后列表

在前端页面上列表 我们首先看看前端页面 我们已经把数据传入前端控制台 再看看我们的代码是怎么写的 我们展示 数据来自图dataList 在这里 我们要把数据填进去 就能展示在前端页面上 用的是前端数据双向绑定 axios发送异步请求 函数 //钩子函数&#xff0c;VUE对象初始化…

RK3568笔记二十九:RTMP推流

若该文为原创文章&#xff0c;转载请注明原文出处。 基于RK3568的RTMP推流测试&#xff0c;此代码是基于勇哥的github代码修改的&#xff0c;源码地址MontaukLaw/3568_rknn_rtmp: rk3568的推理推流 (github.com) 感兴趣的可以clone下来测试。 也可以下载修改后的代码测试。Y…

VirtualBox Ubuntu系统硬盘扩容

1、关闭虚拟机&#xff0c;找到需要扩容的硬盘&#xff0c;修改为新的容量80GB&#xff0c;应用保存。 2、打开VM&#xff0c;进入系统&#xff0c;使用lsblk可以看到硬盘容量已经变为80GB&#xff0c;但硬盘根分区还没有扩容&#xff0c;使用df查看根文件系统也没有扩容。 [19…

Java八股文面试全套真题

Java八股文面试全套真题 一、Redis1.1、你在最近的项目中哪些场景使用了redis呢&#xff1f;1.2、缓存穿透1.3、布隆过滤器1.4、缓存击穿1.5、缓存雪崩1.6、redis做为缓存&#xff0c;mysql的数据如何与redis进行同步呢&#xff1f;&#xff08;双写一致性&#xff09;1.6.1、读…

微信小程序的服务调取

微信小程序的服务调取概述 微信小程序允许开发者通过网络请求与服务器进行交互&#xff0c;从而实现数据的上传和下载。这是通过小程序提供的API&#xff0c;如wx.request、wx.downloadFile、wx.uploadFile等来完成的。这些API使得小程序可以从远程服务器获取数据&#xff0c;…