八、Spring 整合 MyBatis

文章目录

  • 一、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>
        
    </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.mfbz.cn/a/63682.html

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

相关文章

单片机外部晶振故障后自动切换内部晶振——以STM32为例

单片机外部晶振故障后自动切换内部晶振——以STM32为例 作者日期版本说明Dog Tao2023.08.02V1.0发布初始版本 文章目录 单片机外部晶振故障后自动切换内部晶振——以STM32为例背景外部晶振与内部振荡器STM32F103时钟系统STM32F407时钟系统 代码实现系统时钟设置流程时钟源检测…

郭盛华:npm 软件包窃取开发人员的敏感数据

网络安全研究人员在 npm 软件包注册表中发现了一系列新的恶意软件包&#xff0c;这些软件包旨在窃取敏感的开发人员信息。 所有模块的一个共同功能是能够启动 JavaScript&#xff08;“index.js”&#xff09;&#xff0c;该 JavaScript 可以将有价值的信息泄露到远程服务器。…

HCIP 三层交换机

一、实现VLAN间通信 在传统的交换机组网中&#xff0c;默认所有网络都处于同一个广播域&#xff0c;带来了许多问题&#xff0c;VLAN技术的提出&#xff0c;满足了二层组网隔离广播域需求&#xff0c;使得属于不同的VLAN间网络无法通信&#xff0c;但不同VLAN之间又存在着互相…

HTML之表单标签

目录 表单标签 Form表单 定义&#xff1a; 基本语法结构&#xff1a; form属性&#xff1a; enctyoe属性 fieldeset标签 fieldeset属性 legend标签 label标签 优势 label属性 input标签 input属性 input标签中的type属性 text text输入框有以下配套属性 searc bu…

MySQL ROUND、FORMAT数值格式化,以及 返回版本、返回数据库等信息

FORMAT VS ROUND ROUND(数值&#xff0c;n) FORMAT(数值&#xff0c;n) 当 n < 0, FORMAT 整数部分&#xff0c;不会变化&#xff0c; ROUND&#xff0c;整数部分&#xff0c; 根据n的位数&#xff0c;把数值替换成0 当 n>0, 两个效果一样

【数据结构OJ题】移除元素

原题链接&#xff1a;https://leetcode.cn/problems/remove-element/ 目录 1. 题目描述 2. 思路分析 3. 代码实现 1. 题目描述 2. 思路分析 方法一&#xff1a;暴力删除&#xff0c;挪动数据覆盖。即遍历整个nums[ ]数组&#xff0c;遇到值等于val的元素&#xff0c;就将整…

模块高可用性部署概述

高可用三种模式 Ⅰ. 主从热备Ⅱ. 哨兵模式Ⅲ. 集群模式Ⅳ. 番外 总结了Redis的几种高可用方式&#xff0c;对于做后端模块的同学来说&#xff0c;可以根据/或是借鉴其思路做自己的模块可用性部署。 Ⅰ. 主从热备 主从热备&#xff0c;是高可用性中最基础的解决方案&#xff0…

详解Quest 2积分与奖励规则

7月28日&#xff0c;在万众期待中&#xff0c;Mysten Labs在Quest门户网站上宣布了Quest 2的到来。经过严密的筹划&#xff0c;本着真实、公平以及用户至上的原则&#xff0c;现在向大家介绍Quest 2的积分规则以及奖励规则。 温馨提示&#xff1a;第一轮Bullshark Quest是一次精…

模拟实现消息队列项目(系列2) -- 项目前期的准备

目录 前言 1. 需求分析 1.1 核心概念 1.2 核心API 1.3 交换机类型 1.4 持久化 1.5 网络通信 1.6 消息应答 2. 模块划分 结语 前言 我们在上一个系列对于消息队列有了初步的认识,那我们明白了消息队列的用途之后,我们就开始进行我们的项目了,首先我们的项目是仿照Rabb…

【Spring Boot】(三)深入理解 Spring Boot 日志

文章目录 前言一、日志文件的作用二、Spring Boot 中的日志2.1 查看输出的日志信息2.2 日志格式二、Spring Boot 中的日志2.1 查看输出的日志信息2.2 日志格式 三、自定义日志输出3.1 日志框架3.2 日志对象的获取3.3 使用日志对象打印日志 四、日志级别4.1 日志级别的作用4.2 日…

springboot配置文件的使用

目录 1.application.properties是springboot默认的配置文件&#xff0c;但是比较繁琐&#xff0c;一般用.yml文件 2. 配置文件的作用 3.配置文件的使用 1.application.properties是springboot默认的配置文件&#xff0c;但是比较繁琐&#xff0c;一般用.yml文件 ①、properti…

我在leetcode用动态规划炒股

事情是这样的&#xff0c;突然兴起的我在letcode刷题 121. 买卖股票的最佳时机122. 买卖股票的最佳时机 II123. 买卖股票的最佳时机 III 以上三题。 1. 121. 买卖股票的最佳时机 1.1. 暴力遍历&#xff0c;两次遍历 1.1.1. 算法代码 public class Solution {public int Ma…

webpack基础知识八:说说如何借助webpack来优化前端性能?

一、背景 随着前端的项目逐渐扩大&#xff0c;必然会带来的一个问题就是性能 尤其在大型复杂的项目中&#xff0c;前端业务可能因为一个小小的数据依赖&#xff0c;导致整个页面卡顿甚至奔溃 一般项目在完成后&#xff0c;会通过webpack进行打包&#xff0c;利用webpack对前…

使用事件侦听器和 MATLAB GUI 查看 Simulink 信号研究

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

Linux(三):Linux服务器下日常实操命令 (常年更新)

基础命令 cd命令&#xff1a;切换目录 cd &#xff1a;切换当前目录百至其它目录&#xff0c;比如进入/etc目录&#xff0c;则执行 cd /etccd / &#xff1a;在Linux 系统中斜杠“/”表示的是根目录。cd / ,即进入根目录.cd ~&#xff1a;进入用户在该系统的home目录&#…

Linux——设备树

目录 一、Linux 设备树的由来 二、Linux设备树的目的 1.平台识别 2.实时配置 3.设备植入 三、Linux 设备树的使用 1.基本数据格式 2.设备树实例解析 四、使用设备树的LED 驱动 五、习题 一、Linux 设备树的由来 在 Linux 内核源码的ARM 体系结构引入设备树之前&#x…

【CSS】圆形放大的hover效果

效果 index.html <!DOCTYPE html> <html><head><title> Document </title><link type"text/css" rel"styleSheet" href"index.css" /></head><body><div class"avatar"></…

机器学习常用Python库安装

机器学习常用Python库安装 作者日期版本说明Dog Tao2022.06.16V1.0开始建立文档 文章目录 机器学习常用Python库安装Anaconda简介使用镜像源配置 Pip简介镜像源配置 CUDAPytorch安装旧版本 TensorFlowGPU支持说明 DGL简介安装DGLLife RDKitscikit-multilearn Anaconda 简介 …

英语使用场景口语

HOTEL ENGLISH hotel motel inn b&b Process 1.booking a room can i reserve a room? reservation do you have and singles? double room standard room deluxe room presidential suite do you have a pick-up service? 2.checking in where is the recept…

MySQL的数据插入总结(不存在就插入,存在就更新)

MySQL的数据插入总结(不存在就插入&#xff0c;存在就更新) 1. on duplicate key update 当在insert语句后面带上ON DUPLICATE KEY UPDATE 子句&#xff0c;而要插入的行与表中现有记录的惟一索引或主键中产生重复值&#xff0c;那么就会发生旧行的更新&#xff1b;如果插入的…
最新文章