Hibernate current_session_context_class的事务说明

官方文档的原文如下:

The hibernate.current_session_context_class configuration parameter defines which
org.hibernate.context.CurrentSessionContext implementation should be used. Note that for backwards
compatibility, if this config param is not set but a org.hibernate.transaction.TransactionManagerLookup
is configured, Hibernate will use the org.hibernate.context.JTASessionContext. Typically, the value of this
parameter would just name the implementation class to use; for the two out-of-the-box implementations,
however, there are two corresponding short names, "jta" and "thread".
此设置的作用如下:
What does sessionFactory.getCurrentSession() do? First, you can call it
as many times and anywhere you
like, once you get hold of your SessionFactory (easy thanks to
HibernateUtil). The getCurrentSession()
method always returns the "current" unit of work. Remember that we
switched the configuration option for this
mechanism to "thread" in hibernate.cfg.xml? Hence, the scope of the
current unit of work is the current Java
thread that executes our application. However, this is not the full
truth. A Session begins when it is first
needed, when the first call to getCurrentSession() is made. It is then
bound by Hibernate to the current
thread. When the transaction ends, either committed or rolled back,
Hibernate also unbinds the Session from
the thread and closes it for you. If you call getCurrentSession() again,
you get a new Session and can start a
new unit of work. This thread-bound programming model is the most
popular way of using Hibernate.
 意思是说:

sessionFactory.getCurrentSession()可以完成一系列的工作,当调用时,
hibernate将session绑定到当前线程,事务结束后,hibernate
将session从当前线程中释放,并且关闭session。当再次调用getCurrentSession
()时,将得到一个新的session,并重新开始这一系列工作。
这样调用方法如下:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);
session.save(theEvent);
session.getTransaction().commit();

不需要close session了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值