SpringMVC 手动控制事务提交

转载自 https://blog.csdn.net/supingemail/article/details/51183116

增加代码如下:

package tdd.com.jack.qingsonglvxing.service;

import javax.annotation.Resource;

import org.junit.Test;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.ResourceTransactionManager;

import com.jack.qingsonglvxing.service.LogOrderOperateManager;

public class TransactionManagerTest extends BaseManagerTest {
	
	@Resource(name="transactionManager")
	private ResourceTransactionManager transactionManager;
	
	@Resource(name="logOrderOperateManagerImpl")
	private LogOrderOperateManager logOrderOperateManager;
	
	@Test
	public void transaction1() {
		//默认事务回滚,数据库无该条数据
		this.logOrderOperateManager.save("180328094027114800", "A");
	}
	
	@Test
	public void transaction2() {
		//默认事务回滚,数据库无该条数据
		this.logOrderOperateManager.save("180328094027114800", "B");
		throw new RuntimeException("抛出异常");
	}
	
	@Test
	public void transaction3() {
		//默认事务回滚,但是代码中显示开启了新的事务,因此数据库有C1,没有C2
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别,开启新事务
		TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
		this.logOrderOperateManager.save("180328094027114800", "C1");
		transactionManager.commit(status);
		this.logOrderOperateManager.save("180328094027114800", "C2");
	}
	
	@Test
	@Rollback(false)
	public void transaction4() {
		//默认事务不回滚,数据库有该条数据
		this.logOrderOperateManager.save("180328094027114800", "D");
	}
	
	@Test
	@Rollback(false)
	public void transaction5() {
		//默认事务不回滚,数据库有该条数据
		this.logOrderOperateManager.save("180328094027114800", "E");
		throw new RuntimeException("抛出异常");
	}
	
	@Test
	@Rollback(false)
	public void transaction6() {
		//默认事务不回滚,数据库有抛出异常之前的数据
		for (int i=0; i<5; i++) {
			this.logOrderOperateManager.save("180328094027114800", "i="+i);
			if(i>=3) {
				throw new RuntimeException("抛出异常");
			}
		}
	}
}

你可能感兴趣的:(Java语言,框架,体系)