最新最全面的Spring详解(六)——Spring-Mybatis整合

news2025/8/11 11:03:43

前言

在这里插入图片描述

本文为Spring-Mybatis整合相关内容介绍,MyBatis-Spring 可以帮助我们将 MyBatis 代码无缝地整合到 Spring 中。 使用这个类库中的类, Spring 将会加载必要的 MyBatis 工厂类和 session 类。 这个类库也提供一个简单的方式来注入 MyBatis 数据映射器和 SqlSession 到业务层的 bean 中。 而且它也会处理事务, 翻译 MyBatis 的异常到 Spring 的 DataAccessException 异常(数据访问异常,译者注)中。最终,它并 不会依赖于 MyBatis,Spring 或 MyBatis-Spring 来构建应用程序代码。

接下来就按步骤介绍如何通过使用MyBatis-Spring来对Spring和Mybatis进行整合。

📌博主主页:小新要变强 的主页
👉Java全栈学习路线可参考:【Java全栈学习路线】最全的Java学习路线及知识清单,Java自学方向指引,内含最全Java全栈学习技术清单~
👉算法刷题路线可参考:算法刷题路线总结与相关资料分享,内含最详尽的算法刷题路线指南及相关资料分享~
👉Java微服务开源项目可参考:企业级Java微服务开源项目(开源框架,用于学习、毕设、公司项目、私活等,减少开发工作,让您只关注业务!)

↩️本文上接:最新最全面的Spring详解(五)——事务管理

在这里插入图片描述


MyBatis-Spring 可以帮助我们将 MyBatis 代码无缝地整合到 Spring 中。

它将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapper 和 SqlSession 并注入到 bean 中,以及将 Mybatis 的异常转换为 Spring 的 DataAccessException。 最终,可以做到应用代码不依赖于 MyBatis,Spring 或 MyBatis-Spring。

MyBatis-Spring 需要以下版本:

MyBatis-SpringMyBatisSpring FrameworkSpring BatchJava
2.03.5+5.0+4.0+Java 8+
1.33.4+3.2.2+2.1+Java 6+

更多关于MyBatis-Spring的详细内容参考官网:http://mybatis.org/spring/

🍀首先,在pom.xml文件中添加相关包的依赖

要使用 MyBatis-Spring 模块,只需要在类路径下包含 mybatis-spring-2.0.7.jar 文件和相关依赖即可。
如果使用 Maven 作为构建工具,仅需要在 pom.xml 中加入以下代码即可。

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wang</groupId>
    <artifactId>ssm</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>


    <dependencies>
        <!-- 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

        <!-- spring上下文的依赖 包含了aop,bean和core-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.18.RELEASE</version>
        </dependency>
		<!-- springjdbc相关的依赖 包含了jdbcTemplate以及事务-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.18.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.6</version>
        </dependency>

        <!-- 数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
        <!-- 日志 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.6</version>
        </dependency>
        <!-- 数据区驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

        <!-- mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>

        <!-- 整合spring和mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

🍀spring需要管理sqlSessionFactory,通过xml和mapper生成代理由spring统一管理

要和 Spring 一起使用 MyBatis,需要在 Spring 应用上下文中定义至少两样东西:一个 SqlSessionFactory 和至少一个数据映射器类。
在 MyBatis-Spring 中,可使用 SqlSessionFactoryBean来创建 SqlSessionFactory。 要配置这个工厂 bean,只需要把下面代码放在 Spring 的 XML 配置文件中:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
</bean>

spring.xml配置文件:

<?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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://mybatis.org/schema/mybatis-spring
        http://mybatis.org/schema/mybatis-spring.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:property-placeholder location="jdbc.properties"/>
    <context:component-scan base-package="com.wang"/>

    <!--扫描mapper文件-->
    <mybatis:scan base-package="com.wang.mapper"/>

    <!-- 整个整合就是在围绕sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--        <property name="configLocation" value="mybatis-config.xml"/>-->
        <property name="mapperLocations" value="mapper/**/*.xml"/>

        <property name="configuration">
            <bean class="org.apache.ibatis.session.Configuration">
                <property name="mapUnderscoreToCamelCase" value="true"/>
                <property name="logPrefix" value="ydlclass_"/>
            </bean>
        </property>
    </bean>


    <!-- 注入事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${url}"/>
        <property name="driverClassName" value="${driverName}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${password}"/>
    </bean>


    <!-- 声明式事务 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- the transactional semantics... -->
        <tx:attributes>
            <!-- all methods starting with 'get' are read-only -->
            <tx:method name="get*" read-only="true" propagation="SUPPORTS"/>
            <tx:method name="select*" read-only="true" propagation="SUPPORTS"/>
            <!-- other methods use the default transaction settings (see below) -->
            <tx:method name="update*" read-only="false" propagation="REQUIRED"/>
            <tx:method name="delete*" read-only="false" propagation="REQUIRED"/>
            <tx:method name="insert*" read-only="false" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!-- ensure that the above transactional advice runs for any execution
        of an operation defined by the FooService interface -->
    <aop:config>
        <aop:pointcut id="point" expression="within(com.wang.service..*)"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="point"/>
    </aop:config>
    
</beans>

注意: SqlSessionFactory 需要一个 DataSource(数据源)。这可以是任意的 DataSource,只需要和配置其它 Spring 数据库连接一样配置它就可以了。

🍀定义一个mapper和xml

UserMapper.java:

public interface UserMapper {

    User getUser(@Param("userId") int userId);
}

mybatis-config.xml:

<?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>

    <typeAliases>
        <typeAlias type="com.wang.entity.User" alias="user"/>
    </typeAliases>

</configuration>

🍀编写一个测试类进行测试

Test.java:

@Slf4j
public class Test {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext application = new ClassPathXmlApplicationContext("application.xml");
        UserMapper userMapper = application.getBean(UserMapper.class);
        User user = userMapper.getUser(10002);
        log.info("{}",user);
    }
}

MyBatis-Spring的详细内容请参考官网:http://mybatis.org/spring/


后记

在这里插入图片描述
👉Java全栈学习路线可参考:【Java全栈学习路线】最全的Java学习路线及知识清单,Java自学方向指引,内含最全Java全栈学习技术清单~
👉算法刷题路线可参考:算法刷题路线总结与相关资料分享,内含最详尽的算法刷题路线指南及相关资料分享~

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

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

相关文章

用Python构建区块链

区块链 区块链是在计算机网络的节点之间共享数据的分类账(分布式数据库)。作为数据库&#xff0c;区块链以电子格式储存信息。区块链的创新之处在于它保证了数据记录的安全性和真实性&#xff0c;可信性&#xff08;不需要没有可信任的第三方&#xff09;。 区块链和典型数据…

无线数据采集器

背景介绍 近年来&#xff0c;软硬件技术的革新带动了物联网行业的发展&#xff0c;趋使其应用场景不断深化&#xff0c;从工业设备故障诊断到共享经济&#xff0c;再到新能源汽车。调研发现&#xff0c;物联网的核心框架为&#xff1a;通过传感器感知物理世界的状态&#xff0c…

尚医通-手机验证码登录与gateway拦截实现

需求分析 1&#xff0c;登录采取弹出层的形式 2&#xff0c;登录方式&#xff1a; &#xff08;1&#xff09;手机号码手机验证码 &#xff08;2&#xff09;微信扫描 3&#xff0c;无注册界面&#xff0c;第一次登录根据手机号判断系统是否存在&#xff0c;如果不存在则自…

怎么裁剪视频时长?手把手教你裁剪

现在的网络非常方便&#xff0c;我们可以很轻松的在网上找到各种视频进行网课的学习。不过有些网课重点的内容可能不多而且又分散&#xff0c;我们很难做到高效的学习。其实我们可以通过视频裁剪&#xff0c;将需要的视频内容裁剪下来&#xff0c;这样子就方便我们学习啦。那你…

自动驾驶感知算法实战专栏总结:如何打造“高可靠、多冗余、可量化、数据驱动的感知系统”

自动驾驶感知算法实战专栏:https://blog.csdn.net/charmve/category_12097938.html目录 「超融合」感知方案高可靠:对障碍物、红绿灯的识别精度有保证多冗余:各个模块相互支撑、非串行可量化:PRT、仿真场景测试、Profiling数据驱动(全流程闭环)「超融合」感知方案 专注在…

vmware 桥接模式设置桥接到无线网卡

vmware共有三种网络&#xff0c;仅主机Host、NAT和桥接模式。 仅主机Host用于和主机通信的网络。NAT用于网络地址转发上网。桥接模式用于搭建与主机之外的网络的网桥。 在添加桥接模式的网卡后&#xff0c;如果使用有线连接&#xff0c;这个时候&#xff0c;桥接网卡会桥接到的…

消能减震神器之“黏滞阻尼器”的力学原理与应用

作者 | 建源之光&#xff0c;仿真秀专栏作者 一、写在文前 消能阻尼器的基本力学原理主要体现在恢复力模型上&#xff0c;恢复力模型的建立对整体结构模型的动力分析起了便捷作用&#xff0c;便于指导工程实际应用。对于消能阻尼器通常选择以下本构进行模拟&#xff1a; 软钢…

如何利用Airtest做一些简单的装包小任务

1. 前言 很多同学对于Airtest都有一些刻板的印象&#xff0c;觉得Airtest只能截图&#xff0c;然后进行一些简单的点点点操作。 但实际上&#xff0c;抛开Airtest的图像识别点击功能&#xff0c;Airtest还能帮助我们连接设备&#xff0c;然后完成一些别的小任务&#xff0c;比…

CAD .NET 14.1.X DWG/ DXF, PLT 自由转换- CNC

CAD .NET CAD .NET是一个用于在 .NET 环境中开发解决方案的库。它支持 AutoCAD DWG/ DXF、PLT和其他 CAD 格式。 该库可用于广泛的领域&#xff1a; 在所有项目阶段使用工业图纸监控和远程控制程序数控加工数据导出为 CAD 格式使用数据库文件管理系统使用图纸的高度专业化产品…

构建镜像开源工具 buildah

构建镜像开源工具 buildah 文章目录构建镜像开源工具 buildah1. 简介2. 特点3. Buildah 和 Podman4. 安装4.1 CentOS4.2 Ubuntu4.3 RHEL74.4 Fedora5. 命令6. 示例6.1 命令行构建一个 httpd 镜像6.2 Dockerfile 构建6.3 构建镜像脚本&#xff08;代替 Dockerfile&#xff09;1.…

基于JAVA的新闻发布管理系统开发参考【数据库设计、源码、开题报告】

数据库脚本下载地址&#xff1a; https://download.csdn.net/download/itrjxxs_com/86427655 目的 本系统的目的是实现新闻发布系统的基本功能。新闻发布系统提供了不同类型新闻&#xff08;如社会新闻、娱乐新闻和技术前沿新闻等&#xff09; 满足不同用户需求&#xff1b;系…

基于Amos优化器思想推导出来的一些“炼丹策略”

©PaperWeekly 原创 作者 | 苏剑林单位 | 追一科技研究方向 | NLP、神经网络如果将训练模型比喻为“炼丹”&#xff0c;那么“炼丹炉”显然就是优化器了。据传 AdamW 优化器是当前训练神经网络最快的方案&#xff0c;这一点笔者也没有一一对比过&#xff0c;具体情况如何不…

RationalDMIS2022校验测头

一.为什么要校验测头 校验测头的目的有2个 第一是得到测针的实际直径&#xff0c;后续用于探头半径补偿&#xff1b; 第二是得到各角度下测针的偏置&#xff0c;这样不同角度的探针测量出来的数据可以统一到一起&#xff1b; 测头校验包括2部分&#xff1a;定位标准球和测头…

C#程序采用AOT发布,真的可以避免被反编译?

上次跟大家分享过&#xff0c;C#程序反编译与篡改代码的教程《C#程序发布时&#xff0c;一定要好好的保护&#xff0c;不然你会后悔的&#xff01;》&#xff0c;根据这个教程&#xff0c;我们都知道C#程序&#xff0c;发布后必须进行加密混淆&#xff0c;不然就是相当于源码直…

Java 网络编程之 BIO、NIO、AIO

目录I/O 模型BIO基本介绍工作机制编程实例同步阻塞模型&#xff08;一个客户端对应一个服务端&#xff09;BIO模式下一个服务端接收多个客户端伪异步I/O编程&#xff0c;使用线程池基于BIO形式下的文件上传NIOBuffer缓冲区Buffer 类及其子类缓冲区的基本属性Buffer常见方法缓冲…

iNFTnews|Web3走进FIFA世界杯

中心化交易所FTX暴雷留下的阴影还未消退&#xff0c;另一个交易所http://Crypto.com的标志出现在了2022卡塔尔世界杯的赛场上。 据FIFA公告&#xff0c;http://Crypto.com的品牌将于今年11月开始&#xff0c;出现在卡塔尔世界杯体育馆中&#xff0c;且作为赞助商的一部分&#…

Redis 各种用法总结

前言 Redis绝不部分使用场景就是用来做缓存&#xff1b;但是&#xff0c;由于Redis 支持比较丰富的数据结构&#xff0c;因此他能实现的功能并不仅限于缓存&#xff0c;而是可以运用到各种业务场景中&#xff0c;开发出既简洁、又高效的系统; 下面整理了几种 Redis 的妙用场景…

免费录屏软件有哪些?录屏软件下载,认准这3款软件

​在网上活动越来越活跃的今天&#xff0c;人们对于录屏的需求也越来越多了起来。在我们日常生活或者工作生活中经常会使用到录屏功能&#xff0c;录屏的场景和需求变得多样化起来。那么有没有一些好用的免费录屏软件呢&#xff1f;别着急&#xff0c;下面小编带来了3款十分好用…

LabVIEW使用Desktop Execution Trace工具包

LabVIEW使用Desktop Execution Trace工具包 可以使用桌面执行跟踪工具包来调试和优化大型LabVIEW应用程序&#xff0c;包括具有多个循环的应用程序、客户端-服务器架构、动态加载VI等。该工具包从本地或远程计算机桌面上运行的应用程序捕获执行事件&#xff0c;并在表窗格中显…

EPICS -- asynRecord记录使用示例

这个示例演示了如何使用asynRecord记录 1、硬件准备工作 在这里准备了一个型号为NPort 5650-8-DT的Moxa串口服务器&#xff0c;用于一根交叉DB9双母头线缆连接设备上端口2和端口3&#xff0c;使之可以相互通信。 串口服务器配置如下&#xff1a; IP地址&#xff1a;192.168…