我在服务层的方法上添加了@Transactional。
@Transactional(readOnly = false)
public void add(UserFollow uf){
UserFollow db_uf = userFollowRepository.findByUserIdAndFollowUserId(uf.getUserId(), uf.getFollowUserId());
if(db_uf == null) {
userFollowRepository.save(uf);
userCountService.followInc(uf.getFollowUserId(), true);
userCountService.fansInc(uf.getUserId(), true);
throw new RuntimeException();// throw an Exception
}
}
userFollowRepository.save(UF);仍然保存成功,不回滚...
我在应用程序上启用事务管理器。
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableJpaRepositories
@EnableTransactionManagement
public class Application {
@Bean
public AppConfig appConfig() {
return new AppConfig();
}
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}
我将@Transactional移动到控制层,它的工作原理是代码:
@Transactional
@RequestMapping(value="following", method=RequestMethod.POST)
public MyResponse follow(@RequestBody Map<String, Object> allRequestParams){
MyResponse response = new MyResponse();
Integer _userId = (Integer)allRequestParams.get("user_id");
Integer _followUserId = (Integer)allRequestParams.get("follow_user_id");
userFollowService.add(_userId, _followUserId); //this will throw an exception, then rollback
return response;
}
任何人都可以告诉我理由,谢谢!
答案 0 :(得分:-4)
根据http://spring.io/guides/gs/managing-transactions/
@EnableTransactionManagement激活Spring的无缝交易功能,这使得@Transactional功能
所以在你添加了@EnableTransactionManagement
之后就开始工作了