spring在service层的方法报错事务不会回滚

@Transactional(rollbackFor = {Exception.class})
public void insertData() throws Exception {
	// 业务代码1
	business1();
	
	// 业务代码2
	business2();
	
	// 业务代码3
	business3();
}

public void business1() {
	// 此处省略业务操作
}

public void business2() {
	// 此处省略业务操作
}

public void business3() {
	// 此处省略业务操作
}

以上代码在service层执行insertData方法时,business3中的代码执行出错了,business1和business2中的操作都没有回滚

解决方法:

方法一:在service方法中捕获异常,同时向外抛出运行时异常

@Transactional(rollbackFor = {Exception.class})
public void insertData() throws Exception {
	try {
		// 业务代码1
		business1();
		
		// 业务代码2
		business2();
		
		// 业务代码3
		business3();
	} catch(Exception e) {
		throw new RuntimeException(e);
	}
}

方法二:在service方法中捕获异常,同时手动回滚事务

@Transactional(rollbackFor = {Exception.class})
public void insertData() throws Exception {
	try {
		// 业务代码1
		business1();
		
		// 业务代码2
		business2();
		
		// 业务代码3
		business3();
	} catch(Exception e) {
		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); // 事务回滚
	}
}

参考链接:

https://www.cnblogs.com/0201zcr/p/5962578.html

http://www.cuiyongzhi.com/post/90.html

https://blog.csdn.net/paul342/article/details/52330609

你可能感兴趣的:(spring)