1 通过执行 TransactionTemplate类的 execute() 方法:
其中template是 TransactionTemplate 自动装配的
@Test
public void test6() {
transaction.execute((TransactionStatus status) -> {
//DML执行
String sql = "update student set address = ? where username = ?";
template.update(sql, "太阳系", "李七");
//设置回滚
// status.setRollbackOnly();
return null;
});
}
2 通过使用@Transactional 注解:
通过这种方式的 回滚只发生在 运行时异常(或其子类)或者通过设置 rollBackFor 自定义的非运行时异常
@Service
public class BManagerImpl extends BaseManager implements BManager {
/**
* 设置rollback实例
*/
@Transactional
public void rollbackCase1() {
String sql = "delete from student where username = ? ";
template.update(sql, "张三");
throw new RuntimeException("我是故意抛出运行时异常让你删不了");
}
@Transactional
public void rollbackCase2(){
String sql = "delete from student where username = ? ";
template.update(sql, "张三");
throw new MyRuntimeException("我是故意抛出运行时异常让你删不了");
}
@Transactional(rollbackFor = MyException.class)
public void rollbackCase3() throws MyException {
String sql = "delete from student where username = ? ";
template.update(sql, "张三");
throw new MyException("我是故意抛出运行时异常让你删不了");
}
@Transactional
public void commitCase(){
String sql = "delete from student where username = ? ";
template.update(sql, "张三");
}
}
class MyRuntimeException extends RuntimeException {
private static final long serialVersionUID = -6195187154406383710L;
public MyRuntimeException(String msg){
super(msg);
}
}
class MyException extends Exception{
private static final long serialVersionUID = -6195187154406383710L;
public MyException(String msg){
super(msg);
}
}
比较:
声明式的事务控制代码简洁 使用方便; 但是事务的粒度要大于命令式事务控制;