Transaction { @SuppressWarnings("deprecation") public static <T, E extends Throwable> T execute(TransactionCallbackWithException<T, E> callback) throws E { String name = "tx-" + counter.incrementAndGet(); short databaseId = TransactionLegacy.CLOUD_DB; TransactionLegacy currentTxn = TransactionLegacy.currentTxn(false); if (currentTxn != null) { databaseId = currentTxn.getDatabaseId(); } try (final TransactionLegacy txn = TransactionLegacy.open(name, databaseId, false)) { txn.start(); T result = callback.doInTransaction(STATUS); txn.commit(); return result; } }  @SuppressWarnings("deprecation") static T execute(TransactionCallbackWithException<T, E> callback); static T execute(final TransactionCallback<T> callback); @SuppressWarnings("deprecation") static T execute(final short databaseId, TransactionCallbackWithException<T, E> callback); static T execute(final short databaseId, final TransactionCallback<T> callback);  }
@Test public void testCommit() throws Exception { assertEquals(42L, Transaction.execute(new TransactionCallback<Object>() { @Override public Object doInTransaction(TransactionStatus status) { return 42L; } })); verify(conn).setAutoCommit(false); verify(conn, times(1)).commit(); verify(conn, times(0)).rollback(); verify(conn, times(1)).close(); }
@Test public void testRollback() throws Exception { try { Transaction.execute(new TransactionCallback<Object>() { @Override public Object doInTransaction(TransactionStatus status) { throw new RuntimeException("Panic!"); } }); fail(); } catch (RuntimeException e) { assertEquals("Panic!", e.getMessage()); } verify(conn).setAutoCommit(false); verify(conn, times(0)).commit(); verify(conn, times(1)).rollback(); verify(conn, times(1)).close(); }
@Test public void testRollbackWithException() throws Exception { try { Transaction.execute(new TransactionCallbackWithException<Object, FileNotFoundException>() { @Override public Object doInTransaction(TransactionStatus status) throws FileNotFoundException { assertEquals(TransactionLegacy.CLOUD_DB, TransactionLegacy.currentTxn().getDatabaseId().shortValue()); throw new FileNotFoundException("Panic!"); } }); fail(); } catch (FileNotFoundException e) { assertEquals("Panic!", e.getMessage()); } verify(conn).setAutoCommit(false); verify(conn, times(0)).commit(); verify(conn, times(1)).rollback(); verify(conn, times(1)).close(); }
@Test public void testWithExceptionNoReturn() throws Exception { final AtomicInteger i = new AtomicInteger(0); assertTrue(Transaction.execute(new TransactionCallbackWithExceptionNoReturn<FileNotFoundException>() { @Override public void doInTransactionWithoutResult(TransactionStatus status) throws FileNotFoundException { i.incrementAndGet(); } })); assertEquals(1, i.get()); verify(conn).setAutoCommit(false); verify(conn, times(1)).commit(); verify(conn, times(0)).rollback(); verify(conn, times(1)).close(); }