search
HomeJavajavaTutorialIntroduction and methods of DataSourceUitls

Introduction and methods of DataSourceUitls

Jul 26, 2017 pm 05:01 PM
connectionclosure

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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.