1.在启动类加上@EnableTransactionManagement注解
2.在service实现类的方法上加上@Transactional注解,也可加到方法上
示例:
@Service
public class DemoServiceImpl implements DemoService {
@Autowired
PersonRepository personRepository;
@Transactional(rollbackFor = {IllegalArgumentException.class})
@Override
public Person savePersonWithRollBack(Person person) {
Person p = personRepository.save(person);
if (person.getName().equals("sang")) {
throw new IllegalArgumentException("sang 已存在,数据将回滚");
}
return p;
}
@Transactional(noRollbackFor = {IllegalArgumentException.class})
@Override
public Person savePersonWithoutRollBack(Person person) {
Person p = personRepository.save(person);
if (person.getName().equals("sang")) {
throw new IllegalArgumentException("sang已存在,但数据不会回滚");
}
return p;
}
}
属性:
属性 类型 描述
value String 可选的限定描述符,指定使用的事务管理器
propagation enum: Propagation 可选的事务传播行为设置
isolation enum: Isolation 可选的事务隔离级别设置
readOnly boolean 读写或只读事务,默认读写
timeout int (in seconds granularity) 事务超时时间设置
rollbackFor Class对象数组,必须继承自Throwable 导致事务回滚的异常类数组
rollbackForClassName 类名数组,必须继承自Throwable 导致事务回滚的异常类名字数组
noRollbackFor Class对象数组,必须继承自Throwable 不会导致事务回滚的异常类数组
noRollbackForClassName 类名数组,必须继承自Throwable 不会导致事务回滚的异常类名字数组