春季启动@controller @transactional不起作用

时间:2015-05-21 15:38:07

标签: spring-boot spring-data spring-transactions

我在控制器类中有@transactional方法,如下所示: 主要问题是每个服务调用根据日志在其自己的事务中运行。 是否忽略了控制器的事务功能?
我希望学生记录不会被保存为iam在使用其他服务之后抛出异常,但仍然会在数据库中进行更新。我甚至在配置类上有@EnableTransactionManagement。你可以帮我解决这个问题。

@RestController        
@RequestMapping("/api")        
public class Resource {        
@Transactional        
@RequestMapping(value="/test", method = RequestMethod.PUT, produces =         "application/json")        
public StudentDTO updateRecord(@RequestBody StudentDTO DTO) throws             ApplicationException{ 
studentservice.find(1234); //jparepository.findone() runs in one transaction       
studentservice.save(dto); //jparepository.save() runs in one transaction         
testservice.throwException(); // this method throws application exception        
}        

@Configuration        
@ComponentScan(basePackages={"com.student.*"})        
@EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class,              MetricRepositoryAutoConfiguration.class})        
@EnableConfigurationProperties        
@EnableTransactionManagement        
public class Application {        
}       

下面是日志:

[TRACE] org.springframework.transaction.interceptor.TransactionInterceptor -  Getting transaction for   [org.springframework.data.jpa.repository.support.SimpleJpaRepository.findOne]
[TRACE] org.springframework.transaction.interceptor.TransactionInterceptor - Completing transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.findOne]
[TRACE] org.springframework.transaction.interceptor.TransactionInterceptor - Getting transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]
[TRACE] org.springframework.transaction.interceptor.TransactionInterceptor - Completing transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]
[TRACE] org.springframework.transaction.interceptor.TransactionInterceptor -    Completing transaction for [updaterecord] after exception: xx.xx.ApplicationException
[TRACE]   org.springframework.transaction.interceptor.RuleBasedTransactionAttribute -   Applying rules to determine whether transaction should rollback on   xx.xx.ApplicationException
[TRACE]     org.springframework.transaction.interceptor.RuleBasedTransactionAttribute -    Winning rollback rule is: null
[TRACE]   org.springframework.transaction.interceptor.RuleBasedTransactionAttribute - No   relevant rollback rule found: applying default rules 

我使用spring数据jpa,studentservice.find(1234)调用在1个事务中运行的//jparepository.findone()方法 studentservice.save(DTO);调用//jparepository.save()在另一个事务中运行,我们可以从上面的日志中看出

2 个答案:

答案 0 :(得分:2)

最有可能的是,您的交易边界应该在服务层而不是在控制器中声明。

有关详细说明,请查看此处:Why we shouldn't make a Spring MVC controller @Transactional?

答案 1 :(得分:1)

默认情况下,事务将在RuntimeException上回滚。您的ApplicationException是否会延长RuntimeException?如果没有,您可能需要指定rollbackFor的{​​{1}}属性:

@Transactional