XATransactionDataSource implements AutoCloseable { public Connection getConnection() throws SQLException, SystemException, RollbackException { if (CONTAINER_DATASOURCE_NAMES.contains(dataSource.getClass().getSimpleName())) { return dataSource.getConnection(); } Connection result = dataSource.getConnection(); XAConnection xaConnection = XAConnectionFactory.createXAConnection(databaseType, xaDataSource, result); Transaction transaction = xaTransactionManager.getTransactionManager().getTransaction(); if (!enlistedTransactions.get().contains(transaction)) { transaction.enlistResource(new SingleXAResource(resourceName, xaConnection.getXAResource())); transaction.registerSynchronization(new Synchronization() { @Override public void beforeCompletion() { enlistedTransactions.get().remove(transaction); } @Override public void afterCompletion(final int status) { enlistedTransactions.get().clear(); } }); enlistedTransactions.get().add(transaction); } return result; } XATransactionDataSource(final DatabaseType databaseType, final String resourceName, final DataSource dataSource, final XATransactionManager xaTransactionManager); Connection getConnection(); @Override void close();  }
@Test public void assertGetAtomikosConnection() throws SQLException, RollbackException, SystemException { DataSource dataSource = DataSourceUtils.build(AtomikosDataSourceBean.class, DatabaseTypes.getActualDatabaseType("H2"), "ds1"); XATransactionDataSource transactionDataSource = new XATransactionDataSource(DatabaseTypes.getActualDatabaseType("H2"), "ds1", dataSource, xaTransactionManager); try (Connection ignored = transactionDataSource.getConnection()) { verify(xaTransactionManager, times(0)).getTransactionManager(); } }
@Test public void assertGetHikariConnection() throws SQLException, RollbackException, SystemException { DataSource dataSource = DataSourceUtils.build(HikariDataSource.class, DatabaseTypes.getActualDatabaseType("H2"), "ds1"); XATransactionDataSource transactionDataSource = new XATransactionDataSource(DatabaseTypes.getActualDatabaseType("H2"), "ds1", dataSource, xaTransactionManager); try (Connection ignored = transactionDataSource.getConnection()) { verify(transaction).enlistResource(any(SingleXAResource.class)); verify(transaction).registerSynchronization(any(Synchronization.class)); } try (Connection ignored = transactionDataSource.getConnection()) { verify(transaction).enlistResource(any(SingleXAResource.class)); verify(transaction).registerSynchronization(any(Synchronization.class)); } }