2017-10-16 64 views
0

我正在使用spring引導並希望將默認隔離級別更改爲READ_UNCOMMITTED更改隔離級別 - hibernate.connection.isolation不起作用

我搜索並找到屬性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; 
    } 

如何更改使用彈簧啓動的隔離級別?

回答

0

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

擴展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; 
    }