Code Ease Code Ease
  • 个人博客网站 (opens new window)
  • 好用的工具网站 (opens new window)
  • Java核心基础
  • 框架的艺术
  • 分布式与微服务
  • 开发经验大全
  • 设计模式
  • 版本新特性
数据库系列
大数据+AI
  • xxl-job
运维与Linux
  • 基于SpringBoot和BootStrap的论坛网址
  • 基于VuePress的个人博客网站
  • 基于SpringBoot开发的小功能
  • 做一个自己的IDEA插件
程序人生
关于我
  • 分类
  • 标签
  • 归档

神秘的鱼仔

你会累是因为你在走上坡路
  • 个人博客网站 (opens new window)
  • 好用的工具网站 (opens new window)
  • Java核心基础
  • 框架的艺术
  • 分布式与微服务
  • 开发经验大全
  • 设计模式
  • 版本新特性
数据库系列
大数据+AI
  • xxl-job
运维与Linux
  • 基于SpringBoot和BootStrap的论坛网址
  • 基于VuePress的个人博客网站
  • 基于SpringBoot开发的小功能
  • 做一个自己的IDEA插件
程序人生
关于我
  • 分类
  • 标签
  • 归档
服务器
  • Java核心基础

  • 框架的艺术

    • Spring

      • 重新带你走进Spring
      • 控制反转(IOC)和依赖注入(DI)的完美实现
      • 关于Spring中的Bean,一文搞定
      • Spring5竟然可以彻底抛弃xml配置
      • 通俗易懂的AOP切面详解
      • 一文搞定Spring整合Mybatis
        • (一)概述
        • (二)Spring整合Mybatis操作
          • 2.1 引入依赖
          • 2.2 项目准备
          • 2.3 配置mybatis-config.xml
          • 2.4 配置Spring-mybatis配置文件
          • 2.5 使用SqlSessionTemplate
          • 2.6 测试
        • (三)使用SqlSessionDaoSupport再简化
        • (四)总结
      • 事务Transactional注解的参数与失效场景分析
      • 写了两年代码之后再来看看Spring中的Bean
      • 这次终于把Spring的监听器讲明白了
      • 你真的了解Maven吗?
      • 正式发布的Spring AI,能让Java喝上AI赛道的汤吗
    • Mybatis

    • SpringBoot

    • MQ

    • Zookeeper

    • netty

  • 分布式与微服务

  • 开发经验大全

  • 版本新特性

  • Java
  • 框架的艺术
  • Spring
CodeEase
2023-09-20
目录

一文搞定Spring整合Mybatis

作者:鱼仔
博客首页: codeease.top (opens new window)
公众号:Java鱼仔

# (一)概述

有个专门的项目可以用来整合Spring和Mybatis,这里还是先放上官网:

http://mybatis.org/spring/zh/index.html

MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中,首先需要确定版本:

6-1.png

在这里会用最新的版本去做这个整合。

# (二)Spring整合Mybatis操作

# 2.1 引入依赖

在这里我会用spring-jdbc代替mybatis的数据源,因此额外引入了一个spring-jdbc的依赖,其余就是Spring相关依赖和Mybatis相关依赖以及最重要的mybatis-spring

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.4</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.46</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.6</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

# 2.2 项目准备

我这里只搭建一个最简单的项目框架,包含一个用户的实体类,以及一个UserMapper接口和UserMapper.xml文件:

public class User {
    private int id;
    private String name;
    //省略构造方法、get、set、toString
}
1
2
3
4
5

UserMapper

public interface UserMapper {
    List<User> getUserList();
}
1
2
3

UserMapper.xml

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.javayz.mapper.UserMapper">
    <select id="getUserList" resultType="com.javayz.pojo.User">
        select * from user;
    </select>
</mapper>
1
2
3
4
5
6
7
8
9

# 2.3 配置mybatis-config.xml

由于Spring和Mybatis整合后,mybatis-config甚至可以被spring的配置文件所代替,但是为了演示,我依旧会创建这个配置文件:

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--每个mapper.xml都需要在mybatis配置文件中进行配置-->
    <mappers>
        <mapper resource="com/javayz/mapper/UserMapper.xml"/>
    </mappers>
</configuration>
1
2
3
4
5
6
7
8
9
10

# 2.4 配置Spring-mybatis配置文件

这个文件是spring-mybatis的核心配置文件spring.xml

<?xml version="1.0" encoding="UTF8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

        <!--DataSource由Spring管理数据源-->
        <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        </bean>

        <!--配置SqlSessionFactory-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="datasource"/>
            <!--绑定Mybatis配置文件-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
        <!--配置sqlSessionTemplate-->
        <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
            <constructor-arg index="0" ref="sqlSessionFactory"/>
        </bean>

</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

这个配置文件中主要会配置三个东西:DataSource数据源、SqlSessionFactory、SqlSessionTemplate

DataSource数据源就不用多讲了,和Mybatis一样。

在 MyBatis-Spring 中,可使用 SqlSessionFactoryBean来创建 SqlSessionFactory,并给他配置数据源、绑定Mybatis配置文件等。

SqlSessionTemplate是sqlSesson的一个实现,他可以完全代替我们前面所使用的sqlSesson。SqlSessionTemplate 是线程安全的,可以被多个 DAO 或映射器所共享使用。

# 2.5 使用SqlSessionTemplate

我们创建一个UserMapper的实现类UserMapperImpl:

public class UserMapperImpl implements UserMapper {

    private SqlSessionTemplate sqlSessionTemplate;

    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

    public List<User> getUserList() {
        UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
        return mapper.getUserList();

    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

只需要在代码中引入SqlSessionTemplate,就可像SqlSession一样使用它。

创建完成之后记得注入到Spring中,为了把配置和其他的Bean注入分开,我们创建一个applicationContext.xml来统一管理配置文件:

<?xml version="1.0" encoding="UTF8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring.xml"/>

    <bean id="userMapper" class="com.javayz.mapper.UserMapperImpl">
        <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
    </bean>

</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13

# 2.6 测试

 @org.junit.Test
 public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = (UserMapper) context.getBean("userMapper");
        System.out.println(userMapper.getUserList());
}
1
2
3
4
5
6

直接调用mapper即可,不用再像Mybatis一样先创建SqlSessionFactory,再创建SqlSession。

# (三)使用SqlSessionDaoSupport再简化

有没有觉得前面使用SqlSessionTemplate还是有些麻烦,官方给我们提供了更加简单的方式。

使用SqlSessionDaoSupport的话spring-mybatis这个配置文件就不需要再配置SqlSessionTemplate了

<?xml version="1.0" encoding="UTF8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

        <!--DataSource由Spring管理数据源-->
        <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        </bean>
        <!--配置SqlSessionFactory-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="datasource"/>
            <!--绑定Mybatis配置文件-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

然后我们新建一个UserMapperImpl2,它需要继承SqlSessionDaoSupport ,然后直接用getSqlSession()获取到SqlSession即可。

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    public List<User> getUserList() {
        return getSqlSession().getMapper(UserMapper.class).getUserList();
    }
}
1
2
3
4
5

最后注入Bean,需要注入sqlSessionFactory属性:

<bean id="userMapper2" class="com.javayz.mapper.UserMapperImpl2">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
1
2
3

最后测试后获得同样的结果。

# (四)总结

到这里差不多把Spring的基本使用都讲完了,后续会讲一些面试中常考的比较难的知识点,有兴趣可以关注一下。

上次更新: 2025/04/29, 17:22:06
通俗易懂的AOP切面详解
事务Transactional注解的参数与失效场景分析

← 通俗易懂的AOP切面详解 事务Transactional注解的参数与失效场景分析→

最近更新
01
AI大模型部署指南
02-18
02
半个月了,DeepSeek为什么还是服务不可用
02-13
03
Python3.9及3.10安装文档
01-23
更多文章>
Theme by Vdoing | Copyright © 2023-2025 备案图标 浙公网安备33021202002405 | 浙ICP备2023040452号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式