您的位置:首页 > 编程语言 > Java开发

Spring学习笔记十七---事务的转播行为

2016-03-13 00:00 531 查看
spring 事务注解
默认遇到throw new RuntimeException("...");会回滚
需要捕获的throw new Exception("...");不会回滚

// 指定回滚
@Transactional(rollbackFor=Exception.class)
public void methodName() {
// 不会回滚
throw new Exception("...");
}
//指定不回滚
@Transactional(noRollbackFor=Exception.class)
public ItimDaoImpl getItemDaoImpl() {
// 会回滚
throw new RuntimeException("注释");
}

// 如果有事务,那么加入事务,没有的话新建一个(不写的情况下)
@Transactional(propagation=Propagation.REQUIRED)
// 容器不为这个方法开启事务
@Transactional(propagation=Propagation.NOT_SUPPORTED)
// 不管是否存在事务,都创建一个新的事务,原来的挂起,新的执行完毕,继续执行老的事务
@Transactional(propagation=Propagation.REQUIRES_NEW)
// 必须在一个已有的事务中执行,否则抛出异常
@Transactional(propagation=Propagation.MANDATORY)
// 必须在一个没有的事务中执行,否则抛出异常(与Propagation.MANDATORY相反)
@Transactional(propagation=Propagation.NEVER)
// 如果其他bean调用这个方法,在其他bean中声明事务,那就用事务.如果其他bean没有声明事务,那就不用事务.
@Transactional(propagation=Propagation.SUPPORTS)

/*
public void methodName(){
// 本类的修改方法 1
update();
// 调用其他类的修改方法
otherBean.update();
// 本类的修改方法 2
update();
}
other失败了不会影响 本类的修改提交成功
本类update的失败,other也失败
*/
@Transactional(propagation=Propagation.NESTED)
// readOnly=true只读,不能更新,删除
@Transactional (propagation = Propagation.REQUIRED,readOnly=true)
// 设置超时时间
@Transactional (propagation = Propagation.REQUIRED,timeout
3ff0
=30)
// 设置数据库隔离级别
@Transactional (propagation = Propagation.REQUIRED,isolation=Isolation.DEFAULT)
package springjdbc.tx;

import java.util.List;

public interface ICashier {
public void checkout(String userName , List<String> isbns);
}

package springjdbc.tx;

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 java.util.List;

@Service("iCashier")
public class CashierImpl implements  ICashier {
@Autowired
private IBookShopService iBookShopService;

@Transactional(propagation = Propagation.REQUIRED)
//@Transactional(propagation = Propagation.REQUIRES_NEW)
@Override
public void checkout(String userName, List<String> isbns) {
for (String isbn : isbns) {
iBookShopService.purchase(userName, isbn);
}
}
}

package springjdbc.tx;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Arrays;

public class TestTx {
private ApplicationContext ctx = null;

private IBookShopDao iBookShopDao;
private IBookShopService bookShopService;
private ICashier iCashier;
{
ctx = new ClassPathXmlApplicationContext("springjdbc/application.xml");
iBookShopDao = ctx.getBean(IBookShopDao.class);
bookShopService = ctx.getBean(IBookShopService.class);
iCashier = ctx.getBean(ICashier.class);
}

@Test
public void testTransactionPropagation() {
iCashier.checkout("AA", Arrays.asList("1001", "1002"));

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: