首页 > 技术文章 > Spring @Transactional事物配置无效原因

cosmos-wong 2020-05-10 10:03 原文

 

spring @transaction不起作用,Spring事物注意事项

 

1. 在需要事务管理的地方加@Transactional 注解。@Transactional 注解可以被应用于接口定义和接口方法、类定义和类的 public 方法上 。

2. @Transactional 注解只能应用到 public 可见度的方法上 。 如果你在 protected、private 或者 package-visible 的方法上使用 @Transactional 注解,它也不会报错, 但是这个被注解的方法将不会展示已配置的事务设置。

3. 注意仅仅 @Transactional 注解的出现不足于开启事务行为,它仅仅 是一种元数据。必须在配置文件中使用配置元素,才真正开启了事务行为。

重点事项:

Spring事物是基于类和接口的(通俗理解即:在调用的时候不能再同一个类里面被调用,必须调用外面的类去做事物操作

Spring的事物必须是可见的(即:定义的方法必须是public的

 

 

SpringXml配置代码:

<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="dataSourceForSqlServer" />
</bean>

 

核心调用Java代码如下:

package com.pinlive.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.pinlive.JD.util.AccessSignUtil;
import com.pinlive.service.RollbackTestService;
import com.pinlive.transfer.TransferTmSkuService;
import com.pinlive.transfer.TransferVipOrderService;
import com.pinlive.transfer.service.TmallOrderTransferService;

@Controller
public class TestController {


@Autowired
private RollbackTestService rollbackTestService;


@RequestMapping(value = "/test/rollbackTest.do")
public void test(){
for(int i=0; i<10; i++){
rollbackTestService.test();
}
}
}

被调用类代码:

package com.pinlive.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.pinlive.dao.RollbackTestDao;
import com.pinlive.entity.OrderTest;
 
@Service
public class RollbackTestService {


@Autowired
private RollbackTestDao rollbackTestDao;

/**
* 回滚测试
*/
@Transactional(propagation = Propagation.REQUIRED,rollbackFor={Exception.class, RuntimeException.class})
public void test(){

OrderTest orderTest = new OrderTest();
orderTest.setName("weitao");
orderTest.setStudentId("test");
rollbackTestDao.addTest(orderTest);
System.out.println(orderTest.getId());
rollbackTestDao.addLineTest2(orderTest.getId());
}
}

切记:因为spring事物是基于类和接口的所以只能在类里面调用另一个类里面的事物,同一个类里面调用自己类的事物方法是无效的。spring事物也不要频繁使用,在事物处理的同时操作的第一张表会被限制查看的(即被临时锁住)。数据量大的时候会有一定影响。

 

 

事物失效了

 
 
下面事物可以 回滚

原文:http://blog.csdn.net/weitao233136/article/details/51841707

推荐阅读