springmvc + mybatis 事务管理(全注解式)

本文介绍了如何在Spring MVC中使用全注解方式进行MyBatis的事务管理。通过在Controller层启用事务,并配置DataSourceTransactionManager,确保事务的正确执行。测试时直接在Controller中操作,无需Service层。注意点包括:使用@Transactional注解的方法必须是public,且必须抛出异常,同时MySQL数据库引擎需选择InnoDB以支持事务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


我的事务是配置在Controller层  测试中没用Service层,在springMVC的配置文档中开启事务

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


   <!-- (事务管理)transaction manager  dataSource等其他数据库配置信息在spring-context.xml中配置过 根据启动顺序这里能够发现dataSource -->        
    <bean id="transactionManager"  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" /> 



@Controller
@Transactional
public class Test{

@Transactional  //可不添加
public void service(HttpServletRequest request,HttpServletResponse response) throws Exception{

}

}

注意点: 1. @Transactional注解起作用的方法必须是public类型  

      2.该方法必须抛出异常. 

      3.mysql数据库类型的选择(InnoDB) 



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值