云笔记项目-Spring事务学习-传播NEVER

时间:2022-11-16 15:55:46

接下来测试事务传播属性NEVER

Service层

Service层中设置事务传播属性都为NEVER。

LayerT层代码

 package LayerT;

 import javax.annotation.Resource;

 import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional; import Entity.EMP;
import Service.EMPService1;
import Service.EMPService2;
/**
* 测试Never
* @author yangchaolin
*
*/
@Component("neverTest")
public class NeverTest {
@Resource(name="service1")
EMPService1 service1;
@Resource(name="service2")
EMPService2 service2;
/**
* 外层方法没有事务,但是抛出异常
* @param emp1
* @param emp2
*/
public void testNeverWithoutTransaction1(EMP emp1,EMP emp2) {
service1.addEmp1(emp1);
service2.addEmp2(emp2);
throw new RuntimeException();
}
/**
* 外层方法没有事务,内层方法抛出异常
* @param emp1
* @param emp2
*/
public void testNeverWithoutTransaction2(EMP emp1,EMP emp2) {
service1.addEmp1(emp1);
service2.addEmp2WithException(emp2);//就算方法里有异常,也提交了
}
/**
* 外层方法有事务,并且抛出异常
* @param emp1
* @param emp2
*/
@Transactional
public void testNeverWithTransaction1(EMP emp1,EMP emp2) {
service1.addEmp1(emp1);
service2.addEmp2(emp2);
throw new RuntimeException();
}
/**
* 外层方法有事务,都没有异常
* @param emp1
* @param emp2
*/
@Transactional
public void testNeverWithTransaction2(EMP emp1,EMP emp2) {
service1.addEmp1(emp1);
service2.addEmp2(emp2);
} }

测试代码

 package TestCase;

 import org.junit.Test;

 import Entity.EMP;
import LayerT.NeverTest; public class neverTestCase extends baseTest{
@Test
public void test1() {
NeverTest T1=ac.getBean("neverTest",NeverTest.class);
EMP emp1=new EMP("张三",18);
EMP emp2=new EMP("李四",28);
T1.testNeverWithoutTransaction1(emp1, emp2);
}
@Test
public void test2() {
NeverTest T1=ac.getBean("neverTest",NeverTest.class);
EMP emp1=new EMP("张三",18);
EMP emp2=new EMP("李四",28);
T1.testNeverWithoutTransaction2(emp1, emp2);
}
@Test
public void test3() {
NeverTest T1=ac.getBean("neverTest",NeverTest.class);
EMP emp1=new EMP("张三",18);
EMP emp2=new EMP("李四",28);
T1.testNeverWithTransaction1(emp1, emp2);
}
@Test
public void test4() {
NeverTest T1=ac.getBean("neverTest",NeverTest.class);
EMP emp1=new EMP("张三",18);
EMP emp2=new EMP("李四",28);
T1.testNeverWithTransaction1(emp1, emp2);
}
}

测试结果

(1)外层方法没有事务

test1 张三插入,李四插入
test2 张三插入,李四插入

结论:当外层方法没有事务时,才能正常执行。并且不管内层方法有没有抛出异常,事务都提交了,所以定义了NEVER传播属性后,将以非事务方式来执行方法。

(2)外层方法有事务

test3 张三未插入,李四未插入
test4 张三未插入,李四未插入

执行报错:"Existing transaction found for  transaction marked with propagation 'never' "。

结论:当业务方法事务传播属性定义为NEVER时,只要外层方法有事务,执行就会报错,提示外层方法存在有事务,但是内层方法事务被标记为传播属性NEVER,导致无法执行。因此这种设置不会插入数据,只要执行就报错。

参考博客:https://segmentfault.com/a/1190000013341344