版权声明:本文内容来源于网络,如有侵权请联系删除 https://blog.csdn.net/ZyhMemory/article/details/88980944
事务的传播行为
Cashier.java(com.test.spring.tx.Cashier)
package com.test.spring.tx;
import java.util.List;
public interface Cashier {
public void checkout(String username, List<String> isbns);
}
CashierImpl.java(com.test.spring.tx.CashierImpl)
package com.test.spring.tx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service("cashier")
public class CashierImpl implements Cashier {
@Autowired
private BookShopService bookShopService;
@Transactional
@Override
public void checkout(String username, List<String> isbns) {
for (String isbn: isbns){
bookShopService.purchase(username,isbn);
}
}
}
StringTransactionTest.java(com.test.spring.tx.StringTransactionTest)
package com.test.spring.tx;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Arrays;
public class StringTransactionTest {
private ApplicationContext ctx = null;
private Cashier cashier = null;
{
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
cashier = ctx.getBean(Cashier.class);
}
@Test
public void testTeansactionlPropagation(){
cashier.checkout("AA", Arrays.asList("1001","1002"));
}
}
BookShopServiceImpl.java(com.test.spring.tx.BookShopServiceImpl)
在此文件中添加事务注解
情况一(REQUIRES)
// 添加事务注解
// 使用 propagation 指定事务的传播行为,即当前的事务方法被另一个事务方法调用时
// 如何使用事务,默认取值为 REQUIRED,即使用调用方法的事务
@Transactional(propagation = Propagation.REQUIRES)
@Override
public void purchase(String username, String isbn) {}
这样执行后,因为钱不够买俩本书,所以既不会扣钱,也不会减去书的数量
情况二(REQUIRES_NEW)
// 添加事务注解
// 使用 propagation 指定事务的传播行为,即当前的事务方法被另一个事务方法调用时
// REQUIRES_NEW:事务自己的事务,调用的事务方法的事务被挂起。
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Override
public void purchase(String username, String isbn) {}
这样执行后,钱够买一本书,会减去一本书的钱和这本书的数量
其他的传播属性如下(最常用的是前俩种,其他的不经常能用到)
传播属性 | 描述 |
---|---|
PEQUIRED | 如果有事务在运行,当前的方法就在这个事务内运行,否则,就启动一个新的事务,并在自己的事务内运行 |
PEQUIRED_NEW | 当前的方法必须启动新事物,并在它自己的事务内运行,如果有事务正在运行,应该将它挂起 |
SUPPORTS | 如果有事务在运行,当前的方法就在这个事务内运行,否则它可以不运行在事务中。 |
NOT_SUPPORTED | 当前的方法不应该运行在事务中,如果有运行的事务,将它挂起 |
MANDATORY | 当前的方法必须运行在事务内部,如果没有正在运行的事务,就抛出异常 |
NEVER | 当前的方法不应该运行在事务中,如果有运行的事务,就抛出异常 |
NESTED | 如果有事务在运行,当前的方法就应该在这个事务的嵌套事务内运行,否则,就启动一个新的事务,并在它自己的事务内运行。 |