简体   繁体   中英

Sharing database connection with static methods in Java

I'm working on a java web application using Struts 2. Currently, on each page load, I establish a new db connection, and then close this db connection at the end of the request, just before rendering the resulting HTML. So, each request gets its own db connection.

I want to have a bunch of static methods within my model classes, eg things like User.exists( id ) which would return true if the given user id existed, or false if it didn't. Or other utility methods like User.getEmail(id) or User.disable(id) .

My question is, is there a convenient way to share the db connection with these static methods? Having to pass on the connection as a 2nd argument to all these methods, eg User.exists(id, db) would be ugly, and not too convenient.

What about if I obtain a new db connection in each of these utility methods, and close it before returning the result? Would it have any impact on the perfomance? I could need to call these methods 20-30 times within a request some times (such as when validating user input).

Yes, it is possible. For this case where you want that each Thread has its own Connection, you need to use ThreadLocal , since each request spawn its own Thread. You just need to make sure to close the connection at the end of the request, this is achieved using a Filter .

The filter should be before any other Filter to ensure that the connection is closed at the end of the request.

DBUtil:

public class DBUtil {

    private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>();

    public static Connection getConnection() {
        Connection connection = connectionHolder.get();
        if (connection == null) {
            //open the connection (lazy loaded)

            //store it
            connectionHolder.set(connection);

        }
        return connectionHolder.get();
    }

    public static void close() {
        Connection connection = connectionHolder.get();
        if (connection != null) {
            //close the connection

            //remove it from the connection holder
            connectionHolder.remove();
        }
    }

}

DBFilter :

public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {       
    try {
        chain.doFilter(request, response);
    } finally {
        DBUtil.close();         
    }
}

It is better if you use a framework for these kind of things, for example Spring Framework already do this by proxying your services and it handles the connection and transaction also gives you a lot of other features.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM