@Override public synchronized Connection getConnection() throws SQLException { Connection connection = null; Transaction transaction = transactionProvider.get(); // if the transaction holds a connection use that if (transaction != null && transaction.active()) { if (transaction instanceof ConnectionProvider) { ConnectionProvider connectionProvider = (ConnectionProvider) transaction; connection = connectionProvider.getConnection(); } } if (connection == null) { connection = connectionProvider.getConnection(); if (statementCache != null) { connection = new StatementCachingConnection(statementCache, connection); } } // lazily create things that depend on a connection if (platform == null) { platform = new PlatformDelegate(connection); } if (mapping == null) { mapping = new GenericMapping(platform); } return connection; }
@Override public <V> V runInTransaction(Callable<V> callable, @Nullable TransactionIsolation isolation) { Objects.requireNotNull(callable); checkClosed(); Transaction transaction = transactionProvider.get(); if (transaction == null) { throw new TransactionException("no transaction"); } try { transaction.begin(isolation); V result = callable.call(); transaction.commit(); return result; } catch (Exception e) { throw new RollbackException(e); } }
@Test public void testInsertManyToMany() { Person person = randomPerson(); data.insert(person); assertTrue(person.getGroups().toList().isEmpty()); List<Group> added = new ArrayList<>(); try (Transaction transaction = data.transaction().begin()) { for (int i = 0; i < 10; i++) { Group group = new Group(); group.setName("Group" + i); group.setDescription("Some description"); group.setType(GroupType.PRIVATE); data.insert(group); person.getGroups().add(group); added.add(group); } data.update(person); transaction.commit(); } data.refresh(person, Person.GROUPS); assertTrue(added.containsAll(person.getGroups().toList())); }
@Test public void testTransactionRollback() { ArrayList<Integer> ids = new ArrayList<>(); try (Transaction transaction = data.transaction().begin()) { for (int i = 0; i < 10; i++) { Person person = randomPerson(); data.insert(person); assertTrue(person.getId() > 0); ids.add(person.getId()); if (i == 5) { throw new Exception("rollback..."); } } transaction.commit(); } catch (Exception ignored) { } for (Integer id : ids) { Person p = data.select(Person.class).where(Person.ID.equal(id)).get().firstOrNull(); assertNull(p); } }