openSession和getCurrentSession的区别

openSession:获取一个新的Session
getCurrentSession:获得和当前线程绑定的session,在同一个线程中获得同一个session,这样有利于事物的控制。
openSession获得的session也可以维持事物,但必须在同一个service中,getCurrentSession获得的session可以在同一线程的不同service中维持事物。
选择openSession和getCurrentSession原则:
如果需要在同一线程中,保证使用同一个session,选择getCurrentSession
如果在同一线程中,需要不同的session,选择openSession
getCurrentSession获得的session,在commit或者rollback是会自动关闭。
openSession获得的session,需要手动关闭。
建议不管是自动关闭,还是手动关闭都手动关闭
getCurrentSession获得的session需要事物提交,否则会抛异常
getCurrentSession需要配置
hibernate_current_session_context_class thead本地事物
hibernate_current_session_context_class jta全局事物

猜你喜欢

转载自jin8000608172.iteye.com/blog/1752869
今日推荐