2014-11-25 3 views
3

У меня был добавлен @Transactional по методу в слое сервиса.Spring boot @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

Вы можете указать пакеты указанного класса? –

+0

И определения классов, которые обертывают вышеприведенные методы. –

+1

Вам не нужны '@ EnableJpaRepositories' и' @ EnableTransactionManagement' в вашем классе приложений. Spring Boot обнаружит их. Убедитесь, что ваша служба обнаружена с помощью '@ ComponentScan' в вашем классе' Application'. В идеале вам не нужно объявлять 'AppConfig', который должен быть выбран' @ ComponentScan'. –

ответ

-4

По словам http://spring.io/guides/gs/managing-transactions/

@ EnableTransactionManagement активирует функции бесшовной транзакции Spring, что делает функцию @Transactional

так он начал работать после того, как вы добавили @EnableTransactionManagement

Смежные вопросы