【SSM-Spring】Spring事务传播行为

通过propagation 注解事务传播行为

@Transactional(propagation = Propagation.)

事务的传播行为

【SSM-Spring】Spring事务传播行为_第1张图片
【SSM-Spring】Spring事务传播行为_第2张图片

新建需求,同时买两本书

【SSM-Spring】Spring事务传播行为_第3张图片
Cashier:

package SpringTemplate.SpringTX事务准备.事务传播行为;

import java.util.List;

public interface Cashier {
    public void checkout(String username, List 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 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
【SSM-Spring】Spring事务传播行为_第4张图片
【SSM-Spring】Spring事务传播行为_第5张图片

REQUIRES_NEW

【SSM-Spring】Spring事务传播行为_第6张图片
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);
    }
}

【SSM-Spring】Spring事务传播行为_第7张图片
【SSM-Spring】Spring事务传播行为_第8张图片
第一本购买成功,第二本的余额不足,事务失败。

你可能感兴趣的:(SSM-Spring,事务)