自己准备开始教授Java相关的技术,Spring框架是必须让学生学习的框架之一。里面有一个事务相关的

配置,以前刚学习Spring框架的时候有接触过,只是过了很多年,很多东西都已经淡忘。再来回忆一下

如何使用Spring框架配置事务。

使用到的maven坐标如下:

<dependencies>
    <!-- mybatis的依赖支持 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>

    <!-- mysql 驱动依赖 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.33</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.27</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.27</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.3</version>
    </dependency>

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.2.18</version>
    </dependency>

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.7</version>
    </dependency>
</dependencies>

导入的jar包主要有mybatis,mysql驱动,spring相关的jar包,还有mysql连接池的jar包等等。

然后创建一个简单的工程,整个项目的结构大致如下,

测试类里面的代码为:

public class TestApplication {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        CatService catService =(CatService ) ctx.getBean("catService");

        catService.updateCat("西西",1);
        System.out.println("执行完毕!");
    }
}

主要作用是加载Spring的配置类的xml文件,然后获取service类,最后调用service里面的方法来更新数据。

service实现类中的代码为:

public class CatServiceImpl implements CatService {

    private CatDao catDao;

    public void setCatDao(CatDao catDao) {
        this.catDao = catDao;
    }

    @Override
    public int updateCat(String catName, int id) {
        int result = this.catDao.updateCat(catName, id);

        int temp = 10 / 0;

        result = this.catDao.deleteCat(id + 1);
        return result;
    }
}

这里面主要就是注入一个CatDao接口,注意这里必须有setCatDao方法,不然程序也会报错。这个类中只

写了一个方法updateCat,方法中第一步操作是根据ID更新名称;第二步操作是手动产生一个异常,方式为

使用10/0即可,用来测试事务是否正确回滚;第三步就是根据ID逻辑删除一条数据。

dao接口中的代码为:

public interface CatDao {

    int updateCat(@Param("catName") String catName, @Param("id")int id);

    int deleteCat(@Param("id")int id);
}

一个修改的方法,一个删除的方法。

CatDao.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.cat.dao.CatDao">

   <update id="updateCat">
    update cat set cat_name = #{catName, jdbcType = VARCHAR}
    where
    id =  #{id, jdbcType=INTEGER}
   </update>

    <update id="deleteCat" parameterType="int">
    update cat set is_delete = 1
    where
    id =  #{id, jdbcType = INTEGER}
   </update>
</mapper>

一个是修改的方法,一个是逻辑删除的方法。

application.properties配置文件中的配置信息为,主要是数据库连接信息.

driver=com.mysql.cj.jdbc.Driver

url=jdbc:mysql://127.0.0.1:3306/test

name=root

password=root

applicationContext.xml配置文件中的信息为.

<!--引入资源文件-->
<context:property-placeholder location="classpath*:*.properties"/>

<!--创建 druid 连接池对象,dataSource-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" >
    <property name="driverClassName" value="${driver}"/>
    <property name="url" value="${url}"/>
    <property name="username" value="${name}"/>
    <property name="password" value="${password}"/>
</bean>
<!--创建了 sessionFactory对象,用来代替 mybatis中的连接数据库-->
<bean  class="org.mybatis.spring.SqlSessionFactoryBean" >
    <property name="dataSource" ref="dataSource" />
</bean>

<!--映射试下类,mapper-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!--扫描 dao包中的 映射文件,并且 将每个映射文件实例化了一个对象 对相名就是 文件名,开头字母小写-->
    <property name="basePackage" value="com.cat.dao"/>
</bean>

<!--业务层-->
<bean id="catService" class="com.cat.service.impl.CatServiceImpl" >
    <property name="catDao" ref="catDao"/>
</bean>

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

<!-- 配置事务增强 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <!-- 事务属性 -->
    <tx:attributes>
        <tx:method name="*"/>
        <tx:method name="get*" read-only="true"/>
        <tx:method name="find*" read-only="true"/>
        <tx:method name="list*" read-only="true"/>

        <!--增删改 -->
        <tx:method name="insert*" timeout="5000" rollback-for="java.lang.Exception"/>
        <tx:method name="add*" timeout="5000"/>
        <tx:method name="update*" timeout="5000"/>
        <tx:method name="delete*" timeout="5000"/>
    </tx:attributes>
</tx:advice>

<aop:config>
    <!-- 错误配置方式 -->
    <!--<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.service.impl.CatServiceImpl.*.*(..))"/>-->

    <!-- 正确配置方式 -->
    <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.cat.service.impl.CatServiceImpl.*(..))"/>
</aop:config>

遇到的问题一:dao接口和xml文件不在同一个目录下!因此程序在执行的时候,就会报错,

Exception in thread "main" org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.cat.dao.CatDao.updateCat

导致这个问题的原因是,自己在创建xml的包路径时,是直接复制、粘贴com.cat.dao,导致创建的

包名错误。找到项目的根目录查看,如下

因此创建包名的时候,最好是一级一级的创建,直接复制、粘贴就可能会出现问题。

上面的是正确的包名,下面的是错误的包名,凭肉眼看是很难发现错误的,因此在创建

包名的时候一定要注意!

遇到的问题二:CatServiceImpl中注入CatDao的时候,catDao没有手动添加setCatDao方法

时,就会报如下的错误,大致意思就是说没有有效的catDao的set方法。

Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'catDao' of bean class [com.cat.service.impl.CatServiceImpl]: Bean property 'catDao' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

解决方式:添加CatDao成员变量的set方法即可。

遇到的问题三:

dao接口里面的代码

public interface CatDao {

    int updateCat(@Param("catName") String catName, @Param("id")int id);

    int deleteCat(@Param("id")int id);
}

xml里面的代码

<update id="updateCat" parameterType="string">
 update cat set cat_name = #{catName, jdbcType = VARCHAR}
 where
 id =  #{id, jdbcType=INTEGER}
</update>

由于在xml里面设置了parameterType=”string”,因此传入的参数必须为string类型。而自己传入的是

int类型,所以又报一个新的错误如下:

Error setting non null for parameter #2 with JdbcType INTEGER . Try setting a different JdbcType for this parameter or a different configuration property. Cause: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

解决方式为:去除掉这个设置即可parameterType=”string”,就可以传递任意类型的参数。

遇到的问题四:

切入点的配置方式错误,com.cat.service.impl.CatServiceImpl.*.*(..)这个路径是自己从一篇博文中拷贝的,没有做修改最终导致路径错误

<aop:config>

<!-- 错误配置方式 -->

<!--<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.cat.service.impl.CatServiceImpl.*.*(..))"/>-->

<!-- 正确配置方式 -->

<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.cat.service.impl.CatServiceImpl.*(..))"/>

</aop:config>

解决方式:配置为正确的路径 com.cat.service.impl.CatServiceImpl.*(..)即可.区别就在于.*.*还是.*

测试

测试前的数据库数据为

报错信息如下,10 / 0出现错误:

再次查看数据库数据,数据没改变,事务生效。

参考博文

https://www.cnblogs.com/juyss/p/13786370.html

Spring整合mybatis使用xml配置事务的更多相关文章

  1. spring整合mybatis是如何配置事务的?

    作者:郭无心链接:https://www.zhihu.com/question/30206875/answer/84675373来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明 ...

  2. SpringBoot系列-整合Mybatis(XML配置方式)

    目录 一.什么是 MyBatis? 二.整合方式 三.实战 四.测试 本文介绍下SpringBoot整合Mybatis(XML配置方式)的过程. 一.什么是 MyBatis? MyBatis 是一款优 ...

  3. SpringBoot 整合 Mybatis + Mysql——XML配置方式

    一.介绍 SpringBoot有两种方法与数据库建立连接,一种是集成Mybatis,另一种用JdbcTemplate,本文主要讨论集成Mybatis方式. SpringBoot整合Mybatis也有两 ...

  4. SpringBoot整合MyBatis之xml配置

    现在业界比较流行的数据操作层框架 MyBatis,下面就讲解下 Springboot 如何整合 MyBatis,这里使用的是xml配置SQL而不是用注解.主要是 SQL 和业务代码应该隔离,方便和 D ...

  5. spring整合mybatis二种配置

    第一种: <!-- 配置sqlsession --> <bean id="sqlsessionFactory" class="org.mybatis.s ...

  6. spring整合mybatis,ioc容器及声明式事务配置

    步骤: 1.创建jdbc.properties文件,用来管理存放连接数据库的相关信息 jdbc.properties:jdbc.user=root jdbc.password=123456 jdbc. ...

  7. spring整合mybatis(hibernate)配置

    一.Spring整合配置Mybatis spring整合mybatis可以不需要mybatis-config.xml配置文件,直接通过spring配置文件一步到位.一般需要具备如下几个基本配置. 1. ...

  8. spring基础:什么是框架,框架优势,spring优势,耦合内聚,什么是Ioc,IOC配置,set注入,第三方资源配置,综合案例spring整合mybatis实现

    知识点梳理 课堂讲义 1)Spring简介 1.1)什么是框架 源自于建筑学,隶属土木工程,后发展到软件工程领域 软件工程中框架的特点: 经过验证 具有一定功能 半成品 1.2)框架的优势 提高开发效 ...

  9. spring整合mybatis错误:class path resource [config/spring/springmvc.xml] cannot be opened because it does not exist

    spring 整合Mybatis 运行环境:jdk1.7.0_17+tomcat 7 + spring:3.2.0 +mybatis:3.2.7+ eclipse 错误:class path reso ...

  10. spring 整合 mybatis 中数据源的几种配置方式

    因为spring 整合mybatis的过程中, 有好几种整合方式,尤其是数据源那块,经常看到不一样的配置方式,总感觉有点乱,所以今天有空总结下. 一.采用org.mybatis.spring.mapp ...

随机推荐

  1. VRAR概念的定义和要素以及技术定义和应用

    1.概念 一.三个概念的定义和要素. 1.VR,Virtual Reality,虚拟现实 是一种通过计算机模拟真实感的图像,声音和其他感觉,从而复制出一个真实或者假想的场景,并且让人觉得身处这个场景之 ...

  2. Linux-CentOS7 SSH免登陆

    配置三台服务器,如下: 生成密钥 在三台机器(node1\node2\node3)执行以下命令,生成公钥与私钥. ssh-keygen -t rsa 执行该命令之后,按下三个回车即可,然后敲(三个回车 ...

  3. Mygin中间件优化及logger日志中间件

    本篇是mygin的第七篇,参照gin框架,感兴趣的可以从 Mygin第一篇 开始看,Mygin从零开始完全手写,在实现的同时,带你一窥gin框架的核心原理实现. 目的 中间件Middleware优化 ...

  4. 使用Docker部署Tomcat

    目录 使用Docker部署Tomcat 1. 获取镜像 2. 第一次启动tomcat 3.带参数启动 4.查看tomcat日志 5.时区问题 使用Docker部署Tomcat 1. 获取镜像 dock ...

  5. 【C++深度剖析】为什么C++支持函数重载而C不支持--C++程序编译链接过程--符号表生成规则【Linux环境超详细解释C++函数重载底层原理】

    文章目录 前言 Linux环境g++编译器的配置以及一些准备工作 源文件的符号表生成以及分析 尾声 前言 先赞后看好习惯 打字不容易,这都是很用心做的,希望得到支持你 大家的点赞和支持对于我来说是一种 ...

  6. 模式识别实验:基于主成分分析(PCA)的人脸识别

    前言 本文使用Python实现了PCA算法,并使用ORL人脸数据集进行了测试并输出特征脸,简单实现了人脸识别的功能. 1. 准备 ORL人脸数据集共包含40个不同人的400张图像,是在1992年4月至 ...

  7. docker安装oracle数据

    docker安装oracle数据库 1️⃣ 通过docker拉取并启动oracle11g(此版本目前主流),docker换源及安装mysql看Springboot创建项目及测试 - $YX$ - 博客 ...

  8. PHP 编程技巧与优化

    PHP 编程技巧与优化 1. 尽量采用大量的PHP内置函数. 2. 使用echo代替print,并且使用echo的多重参数(译注:指用逗号而不是句点)代替字符串连接 3. 用单引号代替双引号来包含字符 ...

  9. Google_Book_20Things.前言以及前四项学习笔记

    20 THINGS I LEARNED ABOUT BROWSERS AND THE WEB Illustrated by Christoph Niemann. Written by the Goog ...

  10. 单片机 IAP 技术方案设计

    1.前言 关于 IAP 技术,做过 bootloader 的想必很熟悉 (IAP全称 In Application Programming,即应用编程),和 ISP (全称 In System Pro ...