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

时间:2017-10-16 00:25:23

标签: java spring hibernate

我正在使用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;
    }

如何使用弹簧启动更改隔离级别?

1 个答案:

答案 0 :(得分:0)

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

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

@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;
    }