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了。

你可能感兴趣的:(java,thread,工作,Hibernate,session,Class)