首页 > 其他分享 >Spring整合mybatis使用xml配置事务

Spring整合mybatis使用xml配置事务

时间:2023-06-04 14:58:03浏览次数:34  
标签:xml name int Spring cat dependency mybatis com id

  自己准备开始教授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

 

标签:xml,name,int,Spring,cat,dependency,mybatis,com,id
From: https://www.cnblogs.com/yilangcode/p/17455645.html

相关文章

  • MyBatis之一对多抓取策略
    MyBatis之一对多抓取策略1.情况描述如果只需要使用一方中的数据,而不使用多方数据的情况下,在执行过程中不需要发送查询多方的sql语句,需要配置抓取策略为懒加载。2.适用情况适用于一对多的方式一,通过多条sql查询情况。3.抓取策略fetchType(映射文件collection集合映射标签内......
  • 从日志记一次Spring事务完整流程
    spring事务一次完整流程,创建》确认获取连接》完成》提交》释放链接DataSourceTransactionManager//Step1.进入业务方法前,依据事物切面创建事务对象2019-07-0622:34:24,819[main]DEBUGo.s.j.d.DataSourceTransactionManager-Creatingnewtransactionwithname[com......
  • Spring 3.0.5+MyBatis3.0.4整合非完全例子
    基于注解的mybatis和spring整合:[url]http://huangmin001.iteye.com/blog/1185806[/url][color=red]这个文章说的很详细,很值得一看[/color].Maven+SpringMVC+Mybatis【绝非原创,单纯整理】【四】:[url]http://playgod1984.iteye.com/blog/984113[/ur......
  • 在java环境下读取xml文件的方法主要有4种:DOM、SAX、JDOM、JAXB
    dom4j中文乱码[url]http://blog.sina.com.cn/s/blog_3d25e30f0100cyzi.html[/url]org.dom4j.io.XMLWriterxmlWriter=neworg.dom4j.io.XMLWriter(new[color=red]FileOutputStream[/color](fileName));在java环境下读取xml文件的方法主要有4种:DOM、SA......
  • spring jdbcTemplate使用
    参考:springjdbcTemplate使用[url]http://log-cd.iteye.com/blog/215059[/url]SpringJdbcTemplate与事务管理学习[url]http://www.iteye.com/topic/480432[/url]SimpleJdbcTemplate在spring3.1已经过时了,我就改为使用jdbcTemplate和namedParameterJdbcOperations写sql查询......
  • SpringSecurity使用JWT
    SpringSecurity的UsernamePasswordAuthenticationFilter用于处理认证。要整合JWT,只需在认证成功后生成TOKEN并通过响应头写回客户端。在新增一个过滤器用于校验TOKEN。新建SpringBoot项目,添加依赖:<dependency><groupId>org.springframework.boot</groupId>......
  • 1. Mybatis 简介
    1.Mybatis历史MyBatis最初是Apache的一个开源项目iBatis,2010年6月这个项目由ApacheSoftwareFoundation迁移到了GoogleCode。随着开发团队转投GoogleCode旗下,iBatis3.x正式更名为MyBatis。代码于2013年11月迁移到Github。iBatis一词来源于“internet”和“abatis”的组......
  • Spring常用注解
    SVN多版本库环境的搭建OAuth2.0是什么?看这篇文章就够了。前端JavaPython等资源合集大放送使用注解之前要开启自动扫描功能,其中base-package为需要扫描的包(含子包)。<context:component-scanbase-package="cn.com.cms"/>@Configuration把一个类作为一个IoC容器,它的某个方法头上......
  • Spring返回json格式数据的三种方式
    SVN多版本库环境的搭建OAuth2.0是什么?看这篇文章就够了。前端JavaPython等资源合集大放送目前前后端分离大行其道,如何进行前后分类是各个项目需要考虑的问题。如何使用Spring进行前后端分离呢?返回json格式数据是前后端分离的最佳选择。下面介绍使用Spring进行前后端分离的常用三......
  • 【整套视频】spring / springmvc+mybatis
    Spring常用注解redis视频集合,看完这些别说不会redisday88-js对象.rarday87-项目部署和面试指导10.rarday86-订单流程09.rarday85-购物车和订单提交08.rarday84-单品页查询静态化07.rarday83-用户登录和个人中心06.rarday82-商品审核上架和首页筛选05.rarday81-商品添加04.rarday80-......