八、Spring 整合 MyBatis

news2024/10/7 3:28:50

文章目录

  • 一、Spring 整合 MyBatis 的关键点
  • 二、Spring 整合 MyBatis 的步骤
    • 2.1 创建 Maven 项目,并导入相关依赖
    • 2.2 配置 Mybatis 部分
    • 2.3 配置 Spring 部分
    • 2.3 配置测试类


一、Spring 整合 MyBatis 的关键点



1、 将 Mybatis 的 DataSource (数据来源)的创建和管理交给 Spring Ioc 容器来做,并使用第三方数据库连接池来(Druid,C3P0等)取代 MyBatis 内置的数据库连接池

2、将 Mybatis 的 SqlSessionFactroy 交给 Spring Ioc 创建和管理,使用 spring-mybatis 整合jar包中提供的 SqlSessionFactoryBean 类代替项目中的 MyBatisUtil 工具类

3、将MyBatis的接口代理方式生成的实现类,交给Spring IoC容器创建并管理




二、Spring 整合 MyBatis 的步骤


2.1 创建 Maven 项目,并导入相关依赖


  • 创建 maven 项目,并在pom.xml 中整合如下依赖

    注意:如果需要配置 Maven 静态资源过滤问题时,需要保证静态资源路径正确,否则扫描不到

    • 单元测试:junit

    • mybatis 相关依赖

    • 数据库相关依赖 (mysql、Oracle等)

    • 第三方数据库连接池

    • Spring 相关依赖

    • aop 织入器

    • mybatis-spring 整合包【重点】

    • lombok 工具依赖

    • slf4j日志依赖

      • 具体依赖如下所示:

            <dependencies>
                <!-- Junit测试 -->
                <dependency>
                    <groupId>junit</groupId>
                    <artifactId>junit</artifactId>
                    <version>4.12</version>
                    <scope>compile</scope>
                </dependency>
        
                <!-- MyBatis核心Jar包 -->
                <dependency>
                    <groupId>org.mybatis</groupId>
                    <artifactId>mybatis</artifactId>
                    <version>3.4.6</version>
                </dependency>
        
                <!-- MySql驱动 -->
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>5.1.47</version>
                </dependency>
        
                <!-- Lombok工具 -->
                <dependency>
                    <groupId>org.projectlombok</groupId>
                    <artifactId>lombok</artifactId>
                    <version>1.18.12</version>
                    <scope>provided</scope>
                </dependency>
        
                <!-- Spring核心 -->
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context</artifactId>
                    <version>5.3.3</version>
                </dependency>
        
                <!-- Spring-test测试 -->
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-test</artifactId>
                    <version>5.3.3</version>
                </dependency>
        
                <!-- slf4j日志包 -->
                <dependency>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                    <version>1.7.25</version>
                </dependency>
        
                <!-- druid阿里的数据库连接池 -->
                <dependency>
                    <groupId>com.alibaba</groupId>
                    <artifactId>druid</artifactId>
                    <version>1.1.10</version>
                </dependency>
        
                <!-- Spring整合ORM -->
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-orm</artifactId>
                    <version>5.3.3</version>
                </dependency>
        
                <!-- Spring整合MyBatis -->
                <dependency>
                    <groupId>org.mybatis</groupId>
                    <artifactId>mybatis-spring</artifactId>
                    <version>1.3.2</version>
                </dependency>
            </dependencies>
        

2.2 配置 Mybatis 部分


  • 创建实体类

    @Data
    public class User {
    
        private String id;
        private String name;
        private String pwd;
    
    }
    
  • 创建 Mapper 接口

    public interface UserMapper {
    
        List<Users> getUsers();
        
        int addUsers(Users users);
    
        int updateUser(Users users);
    
        int deleteUser(Users users);
    }
    
  • 创建 Mapper 接口对应的 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.sys.mapper.UserMapper" >
    
        <!-- 开启MyBatis自带的二级缓存 -->
        <!--<cache size="1024" eviction="LRU" flushInterval="60000" readOnly="true"/>-->
    
        <select id="getUsers" resultType="com.sys.dto.Users">
            select id,name,pwd from user
        </select>
    
        <insert id="addUsers" parameterType="com.sys.dto.Users">
            insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
        </insert>
    
        <update id="updateUser" parameterType="com.sys.dto.Users">
            update user set name = #{name} where id = #{id}
        </update>
    
        <delete id="deleteUser" parameterType="com.sys.dto.Users">
            delete from user where id = #{id}
        </delete>
    
    </mapper>
    
  • 配置数据源(之前学习 MyBatis 时候都是配置到xml中的,这次维护到 jdbc-config.properties 中,因为不使用 MyBatis 内置连接池,使用第三方数据连接池)

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8
    jdbc.username=root
    jdbc.password=root
    
  • 配置 mybatis-config.xml (配置 MyBatis 缓存)

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    <configuration>
        <!-- 开启延迟加载 该项默认为false,即所有关联属性都会在初始化时加载
             true表示延迟按需加载 -->
        <settings>
            <setting name="lazyLoadingEnabled" value="true"/>
            <!-- 开启二级缓存,这里注释了,不配置默认为一级缓存 -->
            <!-- <setting name="cacheEnabled" value="true"/> -->
        </settings>
        
    </mappers>
    </configuration>
    
  • 配置 log

    log4j.rootLogger=DEBUG, stdout
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n
    
    log4j.logger.java.sql.ResultSet=INFO
    log4j.logger.org.apache=INFO
    log4j.logger.java.sql.Connection=DEBUG
    log4j.logger.java.sql.Statement=DEBUG
    log4j.logger.java.sql.PreparedStatement=DEBUG
    

2.3 配置 Spring 部分


  • 配置 Spring 容器

    • 1、将数据源以 Bean 的形式存储进 Ioc容器
      2、配置 SessionFactory 的 Bean,并将数据源的 Bean 以及 MyBatis 配置文件的路径和 mapper.xml 的映射关系注入到 SessionFactory 的 Bean 中 。(注:SessionFactory :点进源码可以发现,这个类是 mybatis 的实体工具类,所有给属性命名时必须和 SessionFactory 中的属性保持一致)
      3、配置 mapper 接口的自动扫描

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:context="http://www.springframework.org/schema/context"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans.xsd
              http://www.springframework.org/schema/context
              http://www.springframework.org/schema/context/spring-context.xsd">
      
          <!-- 加载数据库连接信息的属性文件 -->
          <context:property-placeholder location="classpath:jdbc-config.properties"/>
      
          <!-- 配置Druid数据源的Bean -->
          <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
              <property name="driverClassName" value="${jdbc.driver}"/>
              <property name="url" value="${jdbc.url}"/>
              <property name="username" value="${jdbc.username}"/>
              <property name="password" value="${jdbc.password}"/>
          </bean>
      
          <!-- 配置SessionFactory的Bean -->
          <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
              <!-- 注入数据源 -->
              <property name="dataSource" ref="dataSource"/>
              <!-- 指定MyBatis配置文件的位置 -->
              <property name="configLocation" value="classpath:mybatis-config.xml"/>
              <!-- 配置 xml 的映射 -->
      	    <property name="mapperLocations" value="classpath:mapper/*.xml"/>
          </bean>
      
          <!-- 配置mapper接口的扫描器,将Mapper接口的实现类自动注入到IoC容器中
           实现类Bean的名称默认为接口类名的首字母小写 -->
          <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
              <!-- basePackage属性指定自动扫描mapper接口所在的包 -->
              <property name="basePackage" value="com.sys.mapper"/>
          </bean>
      </beans>
      

2.3 配置测试类

  • @RunWith注解:

    @RunWith 就是一个运行器
    @RunWith(JUnit4.class) 就是指用JUnit4来运行
    @RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境
    @RunWith(Suite.class) ,就是一套测试集合,
    @ContextConfiguration Spring整合JUnit4测试时,使用注解引入多个配置文件

  • @ContextConfiguration注解:

    @ContextConfiguration这个注解通常与@RunWith(SpringJUnit4ClassRunner.class)联合使用用来测试,这里的用法是通过它来找到 Spring 的配置文件,通过配置文件找到数据源以及 mybatis 配置文件和 映射 mapper 接口等

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:applicationContext.xml")
    public class Test_SpringMyBatis {
    
        @Autowired
        private UserMapper userMapper;
    
        @Test
        public void testFindUserList(){
            Users users = new Users();
            /*users.setId("4");
            users.setName("姚青");
            users.setPwd("123456");
            int i = userMapper.addUsers(users);*/
            /*users.setId("5");
            users.setName("张三");
            int i2 = userMapper.updateUser(users);*/
            /*users.setId("6");
            int i3 = userMapper.deleteUser(users);*/
            List<Users> userList = userMapper.getUsers();
            System.out.println(userList);
        }
    
    }
    
  • 测试结果,增删改查均通过

    在这里插入图片描述


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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

如何恢复已删除的 PDF 文件 - Windows 11、10

在传输数据或共享专业文档时&#xff0c;大多数人依赖PDF文件格式&#xff0c;但很少知道如何恢复意外删除或丢失的PDF文件。这篇文章旨在解释如何有效地恢复 PDF 文件。如果您身边有合适的数据恢复工具&#xff0c;PDF 恢复并不像看起来那么复杂。 便携式文档格式&#xff08…

SpringBoot整合Sfl4j+logback的实践

一、概述 对于一个web项目来说&#xff0c;日志框架是必不可少的&#xff0c;日志的记录可以帮助我们在开发以及维护过程中快速的定位错误。slf4j,log4j,logback,JDK Logging等这些日志框架都是我们常见的日志框架&#xff0c;本文主要介绍这些常见的日志框架关系和SpringBoot…

博客项目测试报告

✏️作者&#xff1a;银河罐头 &#x1f4cb;系列专栏&#xff1a;JavaEE &#x1f332;“种一棵树最好的时间是十年前&#xff0c;其次是现在” 目录 一、项目背景二、项目功能三、测试计划一&#xff09;功能测试二&#xff09;自动化测试三&#xff09;性能测试编写性能测试…

嵌入式Linux驱动开发系列五:Linux系统和HelloWorld

三个问题 了解Hello World程序的执行过程有什么用? 编译和执行&#xff1a;Hello World程序的执行分为两个主要步骤&#xff1a;编译和执行。编译器将源代码转换为可执行文件&#xff0c;然后计算机执行该文件并输出相应的结果。了解这个过程可以帮助我们理解如何将代码转化…

STM32 CubeMX USB_(HID 鼠标和键盘)

STM32 CubeMX STM32 CubeMX USB_HID&#xff08;HID 鼠标和键盘&#xff09; STM32 CubeMX前言 《鼠标》一、STM32 CubeMX 设置USB时钟设置USB使能UBS功能选择 二、代码部分添加代码鼠标发送给PC的数据解析实验效果 《键盘》STM32 CubeMX 设置&#xff08;同上&#xff09;代码…

检测文本是否由AI生成,GPT、文心一言等均能被检测

背景 目前很多机构推出了ChatGPT等AI文本检测工具&#xff0c;但是准确率主打一个模棱两可&#xff0c;基本和抛硬币没啥区别。 先说结论&#xff0c;我们对比了常见的几款AI检测工具&#xff0c;copyleaks检测相比较而言最准确。 检测文本 AI文本片段1 来源&#xff1a;G…

人工智能的缺陷

首先从应用层面理解什么是人工智能&#xff0c;目前人工智能主流应用面包括&#xff1a;自然语言处理领域&#xff0c;代表为chatgpt&#xff0c;我们能用其进行日常交流&#xff0c;问题答疑&#xff0c;论文书写等。计算机视觉领域&#xff0c;代表为人脸识别&#xff0c;现在…

Metashape和PhotoScan中文版软件下载安装地址

Metashape的点云生成功能 Metashape具有强大的点云生成功能&#xff0c;可以将图像转换为精确的三维点云数据。点云数据是进行三维建模和地形分析的重要基础。 在使用Metashape时&#xff0c;用户可以通过使用图像对齐功能生成点云数据。软件根据对齐后的图像生成稠密的点云&a…

c语言-qsort函数

目录 一、函数介绍 二、qsort函数的使用 1、对int类型数组排序 2、对char类型排序 3、对浮点型排序 4.比较字符串 4.1按首字母排序 4.2按长度排序 4.3按字典顺序 5.结构体排序 5.1 多级排序 三、模拟实现qsort函数 【冒泡排序的实现】 【主函数部分】 【代码详解…

二叉树的构建(java基于数组)

前言 二叉树在算法中是经常考察的点&#xff0c;但是要在本地测试的话&#xff0c;就必须自己构建二叉树。在算法题中&#xff0c;一般给我们的都是一个数组&#xff0c;或者是二叉树的形状。因此&#xff0c;需要将数组转换为二叉树&#xff0c;这样才能测试出自己的代码是否符…

Linux文本处理工具和正则表达式

Linux文本处理工具和正则表达式 一.查看、截取和修改文本的工具 1.查看文本的工具 cat 最常用的文件查看命令&#xff1b;当不指明文件或者文件名为一杠’-时&#xff0c;读取标准输入。 cat [OPTION]... [FILE]... -A&#xff1a;显示所有控制符(tab键:^I;行结束符:$) -…

安科瑞故障电弧在体育场馆的应用-安科瑞黄安南

应用场景 一般应用于末端照明回路 功能 1.支持1路剩余电流&#xff0c;外接漏电互感器 2.支持4路温度&#xff0c;外接温度传感器 3.支持32路故障电弧&#xff0c;外接故障电弧传感器 4.支持2DI&#xff0c;2DO 5.声光报警&#xff0c;LCD点阵液晶显示 6.导轨式安装&…

基于ChatYuan-large-v2 语言模型 Fine-tuning 微调训练 广告生成 任务

一、ChatYuan-large-v2 ChatYuan-large-v2是一个开源的支持中英双语的功能型对话语言大模型&#xff0c;与其他 LLM 不同的是模型十分轻量化&#xff0c;并且在轻量化的同时效果相对还不错&#xff0c;仅仅通过0.7B参数量就可以实现10B模型的基础效果&#xff0c;正是其如此的…

基于YOLOv7开发构建MSTAR雷达影像目标检测系统

MSTAR&#xff08;Moving and Stationary Target Acquisition and Recognition&#xff09;数据集是一个基于合成孔径雷达&#xff08;Synthetic Aperture Radar&#xff0c;SAR&#xff09;图像的目标检测和识别数据集。它是针对目标检测、机器学习和模式识别算法的研究和评估…

Visual Studio 2019 详细安装教程(图文版)

前言 Visual Studio 2019 安装包的下载教程、安装教程 教程 博主博客链接&#xff1a;https://blog.csdn.net/m0_74014525 关注博主&#xff0c;后期持续更新系列文章 ********文章附有百度网盘安装包链接********* 系列文章 第一篇&#xff1a;Visual Studio 2019 详细安装教…

MobiSys 2023 | 多用户心跳监测的双重成形声学感知

注1:本文系“无线感知论文速递”系列之一,致力于简洁清晰完整地介绍、解读无线感知领域最新的顶会/顶刊论文(包括但不限于 Nature/Science及其子刊; MobiCom, Sigcom, MobiSys, NSDI, SenSys, Ubicomp; JSAC, 雷达学报 等)。本次介绍的论文是:<<MobiSys’23,Multi-User A…

特殊符号的制作 台风 示例 使用第三方工具 Photoshop 地理信息系统空间分析实验教程 第三版

特殊符号的制作 首先这是一个含有字符的&#xff0c;使用arcgis自带的符号编辑器制作比较困难。所以我们准备采用Adobe Photoshop 来进行制作符号&#xff0c;然后直接导入符号的图片文件作为符号 我们打开ps&#xff0c;根据上面的图片的像素长宽比&#xff0c;设定合适的高度…

高中生python零基础怎么学,python高中生自学行吗

这篇文章主要介绍了高中学历学python好找工作吗&#xff0c;具有一定借鉴价值&#xff0c;需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获&#xff0c;下面让小编带着大家一起了解一下。 学习python的第九天 根据我们前面这几天的学习&#xff0c;我们掌握了Python的…

nginx环境部署

目录 一、yum安装 二、源码安装 三、测试结果 一、yum安装 1、先查找本地yum源上有没有nginx包 yum list | grep nginx 2、rpm安装 rpm -Uvh http://nginx.org/packages/centos/7/x86_64/RPMS/nginx-1.14.2-1.el7_4.ngx.x86_64.rpm 3、查看安装是否成功 rpm -pa | grep…

Pytorch迁移学习使用MobileNet v3网络模型进行猫狗预测二分类

目录 1. MobileNet 1.1 MobileNet v1 1.1.1 深度可分离卷积 1.1.2 宽度和分辨率调整 1.2 MobileNet v2 1.2.1 倒残差模块 1.3 MobileNet v3 1.3.1 MobieNet V3 Block 1.3.2 MobileNet V3-Large网络结构 1.3.3 MobileNet V3预测猫狗二分类问题 送书活动 1. MobileNet …