@After
 public void tearDown() throws Exception {
   while (CurrentUnitOfWork.isStarted()) {
     fail("Test failed to close Unit of Work!!");
     CurrentUnitOfWork.get().rollback();
   }
 }
  @Override
  public Connection getConnection() throws SQLException {
    if (!CurrentUnitOfWork.isStarted()
        || CurrentUnitOfWork.get().phase().isAfter(UnitOfWork.Phase.PREPARE_COMMIT)) {
      return delegate.getConnection();
    }

    UnitOfWork<?> uow = CurrentUnitOfWork.get();
    Connection connection = uow.root().getResource(CONNECTION_RESOURCE_NAME);
    if (connection == null || connection.isClosed()) {
      final Connection delegateConnection = delegate.getConnection();
      connection =
          ConnectionWrapperFactory.wrap(
              delegateConnection,
              UoWAttachedConnection.class,
              new UoWAttachedConnectionImpl(delegateConnection),
              new ConnectionWrapperFactory.NoOpCloseHandler());
      uow.root().resources().put(CONNECTION_RESOURCE_NAME, connection);
      uow.onCommit(
          u -> {
            Connection cx = u.root().getResource(CONNECTION_RESOURCE_NAME);
            try {
              if (!cx.isClosed() && !cx.getAutoCommit()) {
                cx.commit();
              }
            } catch (SQLException e) {
              throw new JdbcException("Unable to commit transaction", e);
            }
          });
      uow.onCleanup(
          u -> {
            Connection cx = u.root().getResource(CONNECTION_RESOURCE_NAME);
            JdbcUtils.closeQuietly(cx);
            if (cx instanceof UoWAttachedConnection) {
              ((UoWAttachedConnection) cx).forceClose();
            }
          });
      uow.onRollback(
          u -> {
            Connection cx = u.root().getResource(CONNECTION_RESOURCE_NAME);
            try {
              if (!cx.isClosed() && !cx.getAutoCommit()) {
                cx.rollback();
              }
            } catch (SQLException ex) {
              throw new JdbcException("Unable to rollback transaction", ex);
            }
          });
    }
    return connection;
  }