Hibernate中使用GetCurrentSession()方法

本文介绍了Hibernate 3.0.1版本引入的SessionFactory.getCurrentSession()方法及其使用方式。此方法简化了Session的管理,并详细讨论了其在本地事务和全局事务中的配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从3.0.1版本开 始,Hibernate增加了SessionFactory.getCurrentSession()方法。
 
采用getCurrentSession()创建的session在commit或rollback时会自动关闭,如果commit()之后再关闭,就会报session已经关闭的错误;但是如果不commit()而执行关闭,虽然不会报什么错误,但是这时观察数据库添加数据是没有成功的,而openSession必须手动关闭。
 
在一个应用程序中,如果DAO 层使用Spring来控制session 的生命周期,则首选getCurrentSession()。
 
在 SessionFactory 启动的时候,Hibernate 会根据配置创建相应的 CurrentSessionContext,在 getCurrentSession()被调用的时候,实际被执行的方法是 CurrentSessionContext.currentSession()。在 currentSession() 执行时,如果当前Session 为空,currentSession 会调用 SessionFactory的openSession。
 
getCurrentSession配置:
 
如果使用的是本地事务(jdbc事务)
 
<property name="hibernate.current_session_context_class">thread</property>
 
如果使用的是全局事务(jta事务)
 
<property name="hibernate.current_session_context_class">jta</property> 
 
 
创建session的另一种方法:
Hibernate官方开发手册的示例中,提供了一个通过ThreadLocal维护Session的示例:这种方法可以使session提交后自动关闭
 
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory
sessionFactory = new
Configuration().configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException(
"Configuration problem: " + ex.getMessage(),
ex
);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException
{
Session s = (Session) session.get();
// Open a new Session, if this Thread has none yet
if (s == null) {
s = sessionFactory.openSession();
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
session.set(null);
if (s != null)
s.close();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值