sinat_32672623 2017-05-02 06:13 采纳率: 0%
浏览 373

关于hibernate 关闭proxool 链接池 链接问题

小弟最近做了一个小型web 项目 框架只使用了 hibernate 5.012 结合proxool连接池,在使用中通过代码查看连接池链接数时发现 hibernate 关闭链接时不能 将链接送回proxool 连接池
public static void closeSession(Session session) {
if (session != null) {
if (session.isOpen()) {
session.close();

        }
    }
}
  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-05 19:53
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    这个问题是由于Hibernate和Proxool的连接模式设置不正确导致的。在Hibernate中,当一个会话关闭时,它应该将所有的连接返回到连接池。

    以下是一个修改后的代码示例,其中我们添加了检查来确保所有打开的连接都被关闭:

    public static void closeSession(Session session) {
        // Check if the session is not closed and it has at least one open connection
        if (session != null && session.isOpen() && !session.isClosed()) {
            // Close the session
            session.close();
    
            // Get the connection from the session
            Connection conn = session.getConnection();
    
            // If there are still connections in the pool, try to reuse them
            while (conn != null) {
                try {
                    conn.close(); // Try to close the connection
                    break; // Stop trying to reuse the connection
                } catch (SQLException e) {
                    // Handle any exceptions that occur during closing the connection
                    e.printStackTrace();
                }
            }
        }
    }
    

    在这个例子中,我们首先检查session是否被关闭并且至少有一个打开的连接。然后,如果存在连接,我们将尝试将其从session中删除,并且如果成功,我们会继续尝试关闭其他连接。请注意,这可能不会总是工作,因为某些数据库可能没有自动回收连接的能力。在这种情况下,你可能需要手动关闭所有未使用的连接。

    评论

报告相同问题?