hibernate中用jdbc注意事项

原则上,hibernate几乎能完成jdbc的所有的操作。

所以在hibernate中几乎不用单独调用jdbc的方法进行sql处理。

但是如果想调用jdbc需要从hibernate的session中获取连接;

	session = HibernateUtil.currentSession(sessionFactoryId);
			conn = session.connection();
获取connection后,就要对连接进行关闭。

如果直接关闭connection,就会出现问题。会报

java.lang.IllegalStateException: Connection is closed

异常

	if(null!=conn){
				try {
					conn.close();
					conn= null;
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
如果直接关闭hibernate中session,不会出现这个问题。

if(null!=session){
				try {
					HibernateUtil.closeSession();
				} catch (HibernateException e) {
					e.printStackTrace();
				}
			}
			
问题解决:

查了一下我们封装的hibernate的closeSession方法:

  public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        session.set(null);
        if (s != null) {
            s.close();
        }
    }
是把session的引用关掉。再关闭s.close();

查一下hibernate中的close()方法:

javadoc上是这样说的:

End the session by releasing the JDBC connection and cleaning up.


close

Connection close()
                 throws HibernateException
End the session by releasing the JDBC connection and cleaning up. It is not strictly necessary to close the session but you must at least disconnect() it.
Returns:
the connection provided by the application or null.
Throws:
HibernateException - Indicates problems cleaning up.
如果直接关闭连接,session就没有关闭,这样当在用session的时候,getCurrentSession的时候,就是上次的session但是上次的session的连接被直接关闭了。因为连接是通过session获得的。没有了connection当再次用这个session执行查询等sql语句的时候,就会报告connection is closed 的错误。

所以从哪里来到哪里去,如果是从session中获取的connection还需要通过关闭session来关闭connection。而不要直接关闭connection
有时候运行了一段时间,才会报这个错误的原因是,一般为了性能上的考虑都会采用连接池技术,当关闭了connection的session再次被调用的时候,就会出现这个错误。如果用的是连接池中的其他session或者新建的session暂时不会报这个错误。




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值