一:在springboot启动类中添加注释 :@EnableTransactionManagement
@EnableDiscoveryClient @SpringBootApplication @EnableFeignClients @EnableTransactionManagement public class DeploymentServiceApplication { public static void main(String[] args){ SpringApplication.run(DeploymentServiceApplication.class, args); } }
二:在相应地方加上注解:@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; } }