Spring Data JPA transaction自定义隔离级别

sulc1iza  于 2023-11-19  发布在  Spring
关注(0)|答案(2)|浏览(134)

给定以下场景:我有一个应用程序运行Sping Boot @SpringBootApplication,并在application.properties中使用Spring Data JPA Boot进行设置:

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级别的隔离,因为应用程序正在水平扩展,偶尔会将冲突数据保存到DB(简单的@Transactional是不够的)。现在,当我尝试执行projectService.save(project)操作时,我得到了一个异常:

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


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

yfwxisqw

yfwxisqw1#

您可以通过在TransactionManager中设置以下内容来启用allowCustomIsolationLevels

transactionManager.setAllowCustomIsolationLevels(true);

字符串

k2fxgqgv

k2fxgqgv2#

my stack:Java 17,Sping Boot 3.0.6,Hibernate 6.2.5.Final,WildFly 28.0.1
为我工作:

@Configuration
public class TransactionConfiguration {

    @Autowired
    public TransactionConfiguration(PlatformTransactionManager transactionManager) {
        JtaTransactionManager jta = (JtaTransactionManager) transactionManager;
        jta.setAllowCustomIsolationLevels(true);
    }
}

字符串

相关问题