use of org.springframework.jdbc.datasource.lookup.IsolationLevelDataSourceRouter in project spring-framework by spring-projects.
the class DataSourceJtaTransactionTests method doTestJtaTransactionWithIsolationLevelDataSourceRouter.
private void doTestJtaTransactionWithIsolationLevelDataSourceRouter(boolean dataSourceLookup) throws Exception {
given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
final DataSource dataSource1 = mock(DataSource.class);
final Connection connection1 = mock(Connection.class);
given(dataSource1.getConnection()).willReturn(connection1);
final DataSource dataSource2 = mock(DataSource.class);
final Connection connection2 = mock(Connection.class);
given(dataSource2.getConnection()).willReturn(connection2);
final IsolationLevelDataSourceRouter dsToUse = new IsolationLevelDataSourceRouter();
Map<Object, Object> targetDataSources = new HashMap<>();
if (dataSourceLookup) {
targetDataSources.put("ISOLATION_REPEATABLE_READ", "ds2");
dsToUse.setDefaultTargetDataSource("ds1");
StaticListableBeanFactory beanFactory = new StaticListableBeanFactory();
beanFactory.addBean("ds1", dataSource1);
beanFactory.addBean("ds2", dataSource2);
dsToUse.setDataSourceLookup(new BeanFactoryDataSourceLookup(beanFactory));
} else {
targetDataSources.put("ISOLATION_REPEATABLE_READ", dataSource2);
dsToUse.setDefaultTargetDataSource(dataSource1);
}
dsToUse.setTargetDataSources(targetDataSources);
dsToUse.afterPropertiesSet();
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
ptm.setAllowCustomIsolationLevels(true);
TransactionTemplate tt = new TransactionTemplate(ptm);
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
Connection c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
assertSame(connection1, c);
DataSourceUtils.releaseConnection(c, dsToUse);
}
});
tt.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
Connection c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
assertSame(connection2, c);
DataSourceUtils.releaseConnection(c, dsToUse);
}
});
verify(userTransaction, times(2)).begin();
verify(userTransaction, times(2)).commit();
verify(connection1).close();
verify(connection2).close();
}
Aggregations