是否应该关闭从休眠会话获得的连接?(Should a connection obtained from a hibernate session be closed?)

我是否需要手动关闭从休眠会话中获取的连接?

如果我这样做,我将关闭连接池中的一个连接吗?

如果不这样,休眠会自动关闭连接吗?

Connection con = null; PreparedStatement ps = null; ResultSet rs = null; String query = "sql query"; try { Session session = this.sessionFactory.getCurrentSession(); con = session.connection(); ps = con.prepareStatement(query); rs = ps.executeQuery(); while (rs.next()) { //read result set } } catch (SQLException exp) { log.error("Error: ", exp); } finally{ if(ps != null) ps.close(); if(con != null) con.close(); //Is this required? }

Do I need to manually close a connection obtained from a hibernate session?

If I do this, will I be closing one of the connections in the connection pool?

Will hibernate automatically close the connection if I do not?

Connection con = null; PreparedStatement ps = null; ResultSet rs = null; String query = "sql query"; try { Session session = this.sessionFactory.getCurrentSession(); con = session.connection(); ps = con.prepareStatement(query); rs = ps.executeQuery(); while (rs.next()) { //read result set } } catch (SQLException exp) { log.error("Error: ", exp); } finally{ if(ps != null) ps.close(); if(con != null) con.close(); //Is this required? }

最满意答案

是的,你应该close连接。 如果您使用的是连接池,则应断开会话,这实际上不会关闭它,但会将其释放回池中。

对于非连接池。 在javadocs中它说明了

注意:在收集垃圾时,Connection对象会自动关闭。 某些致命错误也会关闭Connection对象。

但是,由于它将被关闭,最好自己做。

Yes, you should close the connection. If you are using a connection pool, you should disconnect the session, this will not actually close it, but it will release it back to the pool.

For non-connection pools. In the javadocs it states

Note: A Connection object is automatically closed when it is garbage collected. Certain fatal errors also close a Connection object.

However, as it will be closed, it would be better to do by yourself.

更多推荐