gpt4 book ai didi

spring-boot - spring boot @controller @transactional 不起作用

转载 作者:行者123 更新时间:2023-12-04 02:20:34 26 4
gpt4 key购买 nike

我有 @Transactional Controller 类中的方法如下:
主要问题是每个服务调用都根据日志在自己的事务中运行。

Controller 是否忽略了事务功能?

我希望学生记录不会被保存,因为我在使用另一个服务之后抛出异常,但更新仍然发生在数据库中。我什至有 @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)调用 //jparepository.findone()在 1 个事务中运行的方法 studentservice.save(dto);调用 //jparepository.save()在另一个事务中运行,我们可以从上面的日志中看出

最佳答案

默认情况下,事务在 RuntimeException 上回滚.您的 ApplicationException延长 RuntimeException ?如果没有,您可能需要指定一个 rollbackFor @Transactional 的属性:

@Transactional(rollbackFor=Exception.class)

关于spring-boot - spring boot @controller @transactional 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30378332/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com