Example usage for org.springframework.jdbc.datasource DataSourceUtils doReleaseConnection

List of usage examples for org.springframework.jdbc.datasource DataSourceUtils doReleaseConnection

Introduction

In this page you can find the example usage for org.springframework.jdbc.datasource DataSourceUtils doReleaseConnection.

Prototype

public static void doReleaseConnection(@Nullable Connection con, @Nullable DataSource dataSource)
        throws SQLException 

Source Link

Document

Actually close the given Connection, obtained from the given DataSource.

Usage

From source file:com.alibaba.cobar.client.support.execution.DefaultConcurrentRequestProcessor.java

public List<Object> process(List<ConcurrentRequest> requests) {
    List<Object> resultList = new ArrayList<Object>();

    if (CollectionUtils.isEmpty(requests))
        return resultList;

    List<RequestDepository> requestsDepo = fetchConnectionsAndDepositForLaterUse(requests);
    final CountDownLatch latch = new CountDownLatch(requestsDepo.size());
    List<Future<Object>> futures = new ArrayList<Future<Object>>();
    try {/*  w  w w . j a va  2  s .  c  o  m*/

        for (RequestDepository rdepo : requestsDepo) {
            ConcurrentRequest request = rdepo.getOriginalRequest();
            final SqlMapClientCallback action = request.getAction();
            final Connection connection = rdepo.getConnectionToUse();

            futures.add(request.getExecutor().submit(new Callable<Object>() {
                public Object call() throws Exception {
                    try {
                        return executeWith(connection, action);
                    } finally {
                        latch.countDown();
                    }
                }
            }));
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new ConcurrencyFailureException(
                    "interrupted when processing data access request in concurrency", e);
        }

    } finally {
        for (RequestDepository depo : requestsDepo) {
            Connection springCon = depo.getConnectionToUse();
            DataSource dataSource = depo.getOriginalRequest().getDataSource();
            try {
                if (springCon != null) {
                    if (depo.isTransactionAware()) {
                        springCon.close();
                    } else {
                        DataSourceUtils.doReleaseConnection(springCon, dataSource);
                    }
                }
            } catch (Throwable ex) {
                logger.info("Could not close JDBC Connection", ex);
            }
        }
    }

    fillResultListWithFutureResults(futures, resultList);

    return resultList;
}

From source file:com.haiegoo.framework.ibatis.SqlMapClientMasterSlaveTemplate.java

/**
 * Execute the given data access action on a SqlMapExecutor.
 * @param action callback object that specifies the data access action
 * @return a result object returned by the action, or <code>null</code>
 * @throws DataAccessException in case of SQL Maps errors
 *//*  w ww  . j  av  a 2  s  .c om*/
public <T> T execute(SqlMapClientCallback<T> action, SqlMapClient sqlMapClient) throws DataAccessException {
    Assert.notNull(action, "Callback object must not be null");
    Assert.notNull(sqlMapClient, "No SqlMapClient specified");

    // We always need to use a SqlMapSession, as we need to pass a Spring-managed
    // Connection (potentially transactional) in. This shouldn't be necessary if
    // we run against a TransactionAwareDataSourceProxy underneath, but unfortunately
    // we still need it to make iBATIS batch execution work properly: If iBATIS
    // doesn't recognize an existing transaction, it automatically executes the
    // batch for every single statement...

    SqlMapSession session = sqlMapClient.openSession();
    if (logger.isDebugEnabled()) {
        logger.debug("Opened SqlMapSession [" + session + "] for iBATIS operation");
    }
    Connection ibatisCon = null;

    try {
        Connection springCon = null;
        DataSource dataSource = sqlMapClient.getDataSource();
        boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);

        // Obtain JDBC Connection to operate on...
        try {
            ibatisCon = session.getCurrentConnection();
            if (ibatisCon == null) {
                springCon = (transactionAware ? dataSource.getConnection()
                        : DataSourceUtils.doGetConnection(dataSource));
                session.setUserConnection(springCon);
                if (logger.isDebugEnabled()) {
                    logger.debug("Obtained JDBC Connection [" + springCon + "] for iBATIS operation");
                }
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Reusing JDBC Connection [" + ibatisCon + "] for iBATIS operation");
                }
            }
        } catch (SQLException ex) {
            throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);
        }

        // Execute given callback...
        try {
            return action.doInSqlMapClient(session);
        } catch (SQLException ex) {
            throw getExceptionTranslator().translate("SqlMapClient operation", null, ex);
        } finally {
            try {
                if (springCon != null) {
                    if (transactionAware) {
                        springCon.close();
                    } else {
                        DataSourceUtils.doReleaseConnection(springCon, dataSource);
                    }
                }
            } catch (Throwable ex) {
                logger.debug("Could not close JDBC Connection", ex);
            }
        }

        // Processing finished - potentially session still to be closed.
    } finally {
        // Only close SqlMapSession if we know we've actually opened it
        // at the present level.
        if (ibatisCon == null) {
            session.close();
        }
    }
}

From source file:com.alibaba.cobar.client.CobarSqlMapClientTemplate.java

protected Object executeWith(DataSource dataSource, SqlMapClientCallback action) {
    SqlMapSession session = getSqlMapClient().openSession();

    try {// w  w  w . j a  v  a  2s . c om
        Connection springCon = null;
        boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);

        // Obtain JDBC Connection to operate on...
        try {
            springCon = (transactionAware ? dataSource.getConnection()
                    : DataSourceUtils.doGetConnection(dataSource));
            session.setUserConnection(springCon);
        } catch (SQLException ex) {
            throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);
        }

        try {
            return action.doInSqlMapClient(session);
        } catch (SQLException ex) {
            throw new SQLErrorCodeSQLExceptionTranslator().translate("SqlMapClient operation", null, ex);
        } catch (Throwable t) {
            throw new UncategorizedCobarClientException(
                    "unknown excepton when performing data access operation.", t);
        } finally {
            try {
                if (springCon != null) {
                    if (transactionAware) {
                        springCon.close();
                    } else {
                        DataSourceUtils.doReleaseConnection(springCon, dataSource);
                    }
                }
            } catch (Throwable ex) {
                logger.debug("Could not close JDBC Connection", ex);
            }
        }
        // Processing finished - potentially session still to be closed.
    } finally {
        session.close();
    }
}

From source file:org.sakaiproject.genericdao.springjdbc.JdbcGenericDao.java

/**
 * Allows a developer to do a manual release of the connection,
 * this will cause a new connection to be obtained the next time a method is executed,
 * anything not yet committed for this connection will be rolled back and lost,
 * normally if you are using a DataSource which pools connections then you do not
 * need to worry about this too much, just do it at the end of your work unit
 * //from  w w w. j a  v a 2  s.  com
 * @return true if the connection was closed
 */
public boolean closeConnection() {
    boolean success = false;
    try {
        Connection conn = getConnection();
        try {
            conn.rollback();
        } catch (Exception e) {
            // oh well, keep going
        }
        DataSourceUtils.doReleaseConnection(conn, getDataSource());
        success = true;
    } catch (CannotGetJdbcConnectionException e) {
        logWarn("Could not close connection sucessfully: " + e.getMessage());
    } catch (SQLException e) {
        logWarn("Could not close connection sucessfully: " + e.getMessage());
    }
    return success;
}

From source file:org.artifactory.storage.db.util.DbUtils.java

/**
 * Closes the given connection and just logs any exception.
 *
 * @param con The {@link java.sql.Connection} to close.
 */// w w  w.j av a2 s  .c om
public static void close(@Nullable Connection con, @Nullable DataSource ds) {
    if (con != null) {
        try {
            DataSourceUtils.doReleaseConnection(con, ds);
        } catch (SQLException e) {
            log.trace("Could not close JDBC connection", e);
        } catch (Exception e) {
            log.trace("Unexpected exception when closing JDBC connection", e);
        }
    }
}