Home  >  Article  >  Java  >  Introduction and methods of DataSourceUitls

Introduction and methods of DataSourceUitls

零下一度
零下一度Original
2017-07-26 17:01:351795browse

Introduction to DataSourceUitls

The DataSourceUitls class is located under the org.springframework.jdbc.datasource package. It provides many static methods to obtain JDBC Connection from a javax.sql.DataSource, and provides Spring transaction management. support.

Inside the JdbcTemplate class, DataSourceUtils is used multiple times. In fact, we can also use DataSourceUitls directly in the code to operate Jdbc.

DataSourceUitls gets Connection

getConnection method

Internal implementation

    public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException {
        try {
            return doGetConnection(dataSource);
        }
        catch (SQLException ex) {
            throw new CannotGetJdbcConnectionException("Failed to obtain JDBC Connection", ex);
        }
        catch (IllegalStateException ex) {
            throw new CannotGetJdbcConnectionException("Failed to obtain JDBC Connection: " + ex.getMessage());
        }
    }

It can be seen that by passing in a specified DataSource, you can get a Connection, get The process is implemented by the doGetConnection method. If SQLException and IllegalStateException are thrown, wrap them into CannotGetJdbcConnectionException. In fact, only SQLException and IllegalStateException can be thrown. By looking at the source code of CannotGetJdbcConnectionException, we can find that CannotGetJdbcConnectionException is actually a subclass of DataAccessException. Therefore, it can be said that getConnection will uniformly encapsulate the thrown exception into Spring's DataAccessException.

doGetConnection method

Internal implementation

    public static Connection doGetConnection(DataSource dataSource) throws SQLException {
        Assert.notNull(dataSource, "No DataSource specified");

        ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
        if (conHolder != null && (conHolder.hasConnection() || conHolder.isSynchronizedWithTransaction())) {
            conHolder.requested();
            if (!conHolder.hasConnection()) {
                logger.debug("Fetching resumed JDBC Connection from DataSource");
                conHolder.setConnection(fetchConnection(dataSource));
            }
            return conHolder.getConnection();
        }
        // Else we either got no holder or an empty thread-bound holder here.

        logger.debug("Fetching JDBC Connection from DataSource");
        Connection con = fetchConnection(dataSource);

        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            logger.debug("Registering transaction synchronization for JDBC Connection");
            // Use same Connection for further JDBC actions within the transaction.
            // Thread-bound object will get removed by synchronization at transaction completion.
            ConnectionHolder holderToUse = conHolder;
            if (holderToUse == null) {
                holderToUse = new ConnectionHolder(con);
            }
            else {
                holderToUse.setConnection(con);
            }
            holderToUse.requested();
            TransactionSynchronizationManager.registerSynchronization(
                    new ConnectionSynchronization(holderToUse, dataSource));
            holderToUse.setSynchronizedWithTransaction(true);
            if (holderToUse != conHolder) {
                TransactionSynchronizationManager.bindResource(dataSource, holderToUse);
            }
        }

        return con;
    }

The doGetConnection method is the core method used to actually obtain a Connection. It can be concluded from the source code that if there is no Connection bound to the current thread, a new Connection will be created. If the transaction synchronization of the current thread is active, then Spring transaction management support will be added to the newly created Connection; if If a corresponding Connection exists for the current thread, then there is a current transaction management allocation.

fetchConnection method

fetchConnection is a private method that is not open to the public. It actually performs a simple function: create a new Connection from the current DastaSource. If the new connection fails, an IllegalStateException is thrown. , prompting that a new Connection cannot be obtained.

DataSourceUitls releases Connection

releaseConnection method

Internal implementation

    public static void releaseConnection(@Nullable Connection con, @Nullable DataSource dataSource) {
        try {
            doReleaseConnection(con, dataSource);
        }
        catch (SQLException ex) {
            logger.debug("Could not close JDBC Connection", ex);
        }
        catch (Throwable ex) {
            logger.debug("Unexpected exception on closing JDBC Connection", ex);
        }
    }

The specific implementation of the releaseConnection method is handled by doReleaseConnection. If an exception is thrown, it will only be debugged in the log and will not be thrown externally. Both parameters of this method are NULL.
If con is NULL, this call is ignored; while the other parameter is allowed to be NULL.

doReleaseConnection method

Internal implementation

    public static void doReleaseConnection(@Nullable Connection con, @Nullable DataSource dataSource) throws SQLException {
        if (con == null) {
            return;
        }
        if (dataSource != null) {
            ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
            if (conHolder != null && connectionEquals(conHolder, con)) {
                // It's the transactional Connection: Don't close it.
                conHolder.released();
                return;
            }
        }
        logger.debug("Returning JDBC Connection to DataSource");
        doCloseConnection(con, dataSource);
    }

The doReleaseConnection method is the method that actually releases the Connection. Compared with the releaseConnection method, it completes the processing of the two parameters passed in. The checksum throws a lower level exception. When dataSource is not NULL, release the current connection retained by this ConnectionHolder so that the current Connection can be reused, which is very helpful for improving the performance of Jdbc operations. If dataSource is null, choose to close the connection directly.

DataSourceUitls closes Connection

doCloseConnection method

Internal implementation

    public static void doCloseConnection(Connection con, @Nullable DataSource dataSource) throws SQLException {
        if (!(dataSource instanceof SmartDataSource) || ((SmartDataSource) dataSource).shouldClose(con)) {
            con.close();
        }
    }

In the doReleaseConnection method, we have learned that doCloseConnection will be executed when the datasource is NULL method. In fact, the Connection is actually closed only when the dataSource does not implement the org.springframework.jdbc.datasource.SmartDataSource interface or when the dataSource implements the org.springframework.jdbc.datasource.SmartDataSource interface and is allowed to be closed.

org.springframework.jdbc.datasource.SmartDataSource interface is an extension of javax.sql.DataSource interface, returning the Jdbc connection in an unpackaged form. Classes that implement this interface can query whether the Connection should be closed after completing the operation. Such checks are automatically performed in Srping and DataSourceUitls and JdbcTemplate.

The above is the detailed content of Introduction and methods of DataSourceUitls. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn