繁体   English   中英

与Java中的静态方法共享数据库连接

[英]Sharing database connection with static methods in Java

我正在使用Struts 2开发Java Web应用程序。目前,在每次页面加载时,我都会建立一个新的数据库连接,然后在呈现结果HTML之前,在请求结束时关闭该数据库连接。 因此,每个请求都有自己的数据库连接。

我想在我的模型类中拥有一堆静态方法,例如User.exists( id )类的东西,如果给定的用户ID存在,则返回true,否则返回false。 或其他实用程序方法,例如User.getEmail(id)User.disable(id)

我的问题是,是否有一种方便的方法与这些静态方法共享数据库连接? 必须将连接作为所有这些方法的第二个参数传递,例如User.exists(id, db)很难看,而且不太方便。

如果我在上述每个实用程序方法中都获得了一个新的数据库连接,并在返回结果之前将其关闭,该怎么办? 对性能有影响吗? 我可能需要在请求中多次调用这些方法20-30次(例如,验证用户输入时)。

对的,这是可能的。 对于这种情况,您希望每个线程都有自己的连接,则需要使用ThreadLocal ,因为每个请求都产生自己的线程。 您只需要确保在请求结束时关闭连接即可,这是使用Filter实现的。

该过滤器应位于任何其他过滤器之前,以确保在请求结束时关闭连接。

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();         
    }
}

最好将框架用于此类事情,例如Spring Framework已经通过代理服务来做到这一点,并且它处理连接和事务还为您提供了许多其他功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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