Hibernate 支持三种方式 对Session 对象的生命周期进行管理
1.session与本地线程绑定:
主要用于web开发。
1)通过hibernate.cfg.xml 配置:
在框架中配置hibernate.current_session_context_class 。
<hibernate-configuration>
<session-factory>
<!-- 将Session的生命周期与当前线程绑定 -->
<property name="hibernate.current_session_context_class">thread</property>
2)SessionFactory:
多次使用SessionFactory提供的openSession方法获得的Session对象都不同。getCurrentSession()方法可以获得与当前线程绑定的Session对象。必须在hibernate.cfg.xml配置与线程绑定后才能使用。
public void testSession() {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
Session session1 = sessionFactory.openSession();
Session session2 = sessionFactory.openSession();
System.out.println(session1 == session2); //false
//获得与当前线程绑定的session
Session session3 = sessionFactory.getCurrentSession();
Session session4 = sessionFactory.getCurrentSession();
System.out.println(session3 == session4); //true
}
3)注意点:
使用getCurrentSession时,Session由线程管理,当事务提交时,线程会自动关闭Session。此时手动调用 session.close()方法会报错。
public void testSession() {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.getCurrentSession();
Transaction transaction = session.beginTransaction();
PojoUser user = (PojoUser) session.get(PojoUser.class, 2);
System.out.println(user);
//因为通过sessionFactory.getCurrentSession()得到的session由线程管理,
//当事务提交后线程会关闭session。
transaction.commit();
//再次关闭会报错
session.close();
}
手动关闭session报错:
org.hibernate.SessionException: Session was already closed
at org.hibernate.internal.SessionImpl.close(SessionImpl.java:344)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
at $Proxy5.close(Unknown Source)
2.Session与JTA事务绑定:
主要用于分布式 数据库会话 事务管理。需要服务器支持JTA,tomcat不支持,weblogic支持JTA。
3.通过程序管理:
手动创建、关闭。
- end