Я добавил @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;
}
кто-нибудь может сказать мне причину, спасибо!
@EnableJpaRepositories
и@EnableTransactionManagement
в вашем классе приложения. Spring Boot обнаружит их. Убедитесь, что ваша служба обнаружена@ComponentScan
в вашемApplication
классе. В идеале вам не нужно объявлятьAppConfig
, так как это должно быть подхвачено@ComponentScan
. - person M. Deinum   schedule 25.11.2014@Transactional add
из того же класса или из другого класса? - person chrylis -cautiouslyoptimistic-   schedule 25.11.2014