【问题标题】:Spring Data JPA transaction custom isolation levelSpring Data JPA 事务自定义隔离级别
【发布时间】:2016-09-11 16:22:04
【问题描述】:

鉴于以下情况: 我有一个使用 Spring Boot @SpringBootApplication 运行的应用程序,并在 application.properties 中使用 Spring Data JPA 数据源进行设置:

spring.datasource.url=jdbc:mysql://foo.bar.com:12345
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

并且没有额外的 java/xml 配置。

我有几个服务:

@Service
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    ProjectRepository projectRepository;

    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public Project save(Project project) {
        // there might be some additional logic here, besides the action on repository
        return projectRepository.save(project);
    }
}

和存储库:

@Repository
public interface ProjectRepository extends CrudRepository<Project, Long> {}

因为它在上面的代码中,我发现自己需要 SERIALIZABLE 级别的隔离,因为应用程序被水平扩展并且偶尔将冲突的数据保存到数据库(仅仅 @Transactional 是不够的) .现在,当我尝试执行 projectService.save(project) 操作时,我得到一个异常:

"exception": "org.springframework.transaction.InvalidIsolationLevelException",
"message": "JtaTransactionManager does not support custom isolation levels by default - switch 'allowCustomIsolationLevels' to 'true'",

是否可以使用 java 配置启用这些自定义隔离级别?

【问题讨论】:

    标签: java spring spring-boot spring-data spring-data-jpa


    【解决方案1】:

    您可以通过在TransactionManager 中进行以下设置来启用allowCustomIsolationLevels

    transactionManager.setAllowCustomIsolationLevels(true);
    

    【讨论】:

    • 我的问题更多是指我不知道如何访问tramsactionManager 才能设置该值。可以用@EnableTransactionManagement 以某种方式完成吗?
    • 您将在 applicationcontext.xml 或其他一些 xml 文件中定义一个事务管理器。请在transactionManager的bean定义中设置
    • 情况是我不使用基于xml的spring配置。可以用java config来完成吗?
    • @Bean public PlatformTransactionManager platformTransactionManager() { return new JtaTransactionManager(); }
    猜你喜欢
    • 1970-01-01
    • 2015-07-21
    • 2011-02-24
    • 2020-06-07
    • 2018-05-04
    • 2015-10-18
    • 2011-03-19
    • 1970-01-01
    • 2015-01-06
    相关资源
    最近更新 更多