gpt4 book ai didi

java - 更改隔离级别 - hibernate.connection.isolation 不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 11:02:18 26 4
gpt4 key购买 nike

我正在使用 Spring Boot,并且希望将默认隔离级别更改为 READ_UNCOMMITTED

我搜索并找到了属性hibernate.connection.isolation,但我尝试了一下,但没有成功。

我的配置是这样的:

private Properties additionalJpaProperties() {
Properties properties = new Properties();

properties.setProperty("hibernate.hbm2ddl.auto", "validate");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
properties.setProperty("hibernate.connection.isolation", String.valueOf(Connection.TRANSACTION_READ_UNCOMMITTED));

return properties;
}

@Primary
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) throws SQLException {

LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan(this.packages);
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(this.additionalJpaProperties());
return em;
}

如何使用 Spring Boot 更改隔离级别?

最佳答案

如果有人需要解决方案。我找到的唯一解决方案是:

扩展HibernateJpaDialect类并实现beginTransaction方法来设置事务隔离。它看起来像这样:

@Service
public class CustomHibernateJpaDialect extends HibernateJpaDialect {

@Override
public Object beginTransaction(final EntityManager entityManager,
final TransactionDefinition definition) throws PersistenceException,
SQLException, TransactionException {

Session session = getSession(entityManager);

if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
session.getTransaction().setTimeout(definition.getTimeout());
}

entityManager.getTransaction().begin();

session.doWork(new Work() {
public void execute(Connection connection) throws SQLException {
DataSourceUtils.prepareConnectionForTransaction(connection, definition);
connection.setTransactionIsolation(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
}
});

return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName());
}

}

并且在entityManagerFactory的配置中需要设置创建的方言:

    @Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
DataSource dataSource,
CustomHibernateJpaDialect customHibernateJpaDialect) throws SQLException {

LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);

JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

em.setJpaVendorAdapter(vendorAdapter);
em.setJpaDialect(customHibernateJpaDialect);

return em;
}

关于java - 更改隔离级别 - hibernate.connection.isolation 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46761383/

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