Welcome 微信登录

首页 / 软件开发 / JAVA / hibernate3学习笔记(六) Session管理

hibernate3学习笔记(六) Session管理2011-02-02请注意,在hibernate中SessionFactory是被设计成线程安全(Thread-safe)的,遗憾的是,Session却线程不安全。

这就意味着:有可能多个线程共享并操作同一个Session从而很容易使数据混乱。

解决的办法如下:(其实hibernate的文档中早已经提过了)

新建HibernateUtil类:

1.import org.apache.commons.logging.Log;
2.import org.apache.commons.logging.LogFactory;
3.import org.hibernate.*;
4.import org.hibernate.cfg.*;
5.
6.public class HibernateUtil {
7.private static Log log = LogFactory.getLog(HibernateUtil.class);
8.private static final SessionFactory sessionFactory;
9.10.static {
11.try {
12.// Create the SessionFactory13.sessionFactory = new Configuration().configure()
14..buildSessionFactory();
15.} catch (Throwable ex) {
16.// Make sure you log the exception, as it might be swallowed17.log.error("Initial SessionFactory creation failed.", ex);
18.throw new ExceptionInInitializerError(ex);
19.}
20.}
21.22.public static final ThreadLocal session = new ThreadLocal();
23.24.public static Session currentSession() {
25.Session s = (Session) session.get();
26.27.// Open a new Session, if this Thread has none yet28.if (s == null) {
29.s = sessionFactory.openSession();
30.session.set(s);
31.}
32.33.return s;
34.}
35.36.public static void closeSession() {
37.Session s = (Session) session.get();
38.39.if (s != null) {
40.s.close();
41.}
42.43.session.set(null);
44.}
45.}