Spring boot @Transactional not working
I had @Transactional added for the service level method.
@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); still persists crash, not rollback ...
i enable the transaction manager in the application.
@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);
}
}
i move @Transactional to control layer, it works, code:
@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;
}
can someone tell me the reason, thanks!
+3
source to share
1 answer
According to http://spring.io/guides/gs/managing-transactions/
@EnableTransactionManagement activates Spring's seamless transaction functionality, making the @Transactional function
so it started working after adding @EnableTransactionManagement
-4
source to share