通过propagation 注解事务传播行为
@Transactional(propagation = Propagation.)
事务的传播行为
新建需求,同时买两本书
Cashier:
package SpringTemplate.SpringTX事务准备.事务传播行为;
import java.util.List;
public interface Cashier {
public void checkout(String username, List<String> isbn);
}
CashierImpl:
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);
}
}
}
Test:
import java.util.Arrays;
public class Test {
private ApplicationContext ac = null;
private BookShopService bookShopService =null;
private BookShopDao bookShopDao =null;
private Cashier cashier = null;
{
ac = new ClassPathXmlApplicationContext(
"classpath:JDBCTEM/SpringTXcontext.xml"
);
bookShopDao = ac.getBean(BookShopDao.class);
bookShopService = ac.getBean(BookShopService.class);
cashier =ac.getBean(Cashier.class);
}
@org.junit.Test
public void TwoTransactionalTest(){
cashier.checkout("AA", Arrays.asList("1001","1002"));
}
}
默认传播行为 REQUIRED,使用调用方法的事务
@Transactional(propagation = Propagation.REQUIRED)
余额不足时,一本也没成功,因为使用的是同一个事务,两个行为必须都失败或者都成功
propagation
REQUIRES_NEW
Cashier 购买两本书的方法调用了 BookShopService中没次买一本的方法。默认他们是一个事务。但是 BookShopService要是有自己单独的事务方法_NEW
就可以一本能成功的时候就成功了。
BookService中的代码:
@Service("bookShopService")
public class BookShopServiceImpl implements BookShopService {
@Autowired
private BookShopDao bookShopDao;
//2 添加事务注解
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Override
public void purchase(String username, String isbn) {
int price = bookShopDao.findBookPriceByIsbn(isbn);
bookShopDao.updateBookStock(isbn);
bookShopDao.updateUserAccount(username,price);
}
}
第一本购买成功,第二本的余额不足,事务失败。