hibernate的Configuration问题

是不是每次都需要用一个Configuration实例来buildSessionFactory从而得到一个SessionFactory呢?

如果不是在EJB环境下,可以自己写一个工厂方法,实现SessionFactory的Singleton。如果在EJB环境下,可以将它配置到JNDI上。总之,只需要开始的时候配置一次,以后都不需要再配置了。参考代码如下:


import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.MappingException;

public class HibernateSessionFactory {

private static SessionFactory sf = null;

public static synchronized Session getSession() throws HibernateException {
Configuration conf = null;
if (sf == null) {
try {
conf = new Configuration()
.addClass(Teacher.class)
.addClass(...class); // 把数据库表映射的POJO添加到这里
} catch (MappingException e) {
System.out.println(e.getMessage());
return null;
}
sf = conf.buildSessionFactory();
}
return sf.openSession();
}

}

在自己的程序里面写:
Session s = HibernateSessionFactory.getSession();
就可以了。

多谢robbin。

如果我要用在struts的action中,用工厂会不会有问题呢?
前面看你们讨论ThreadLocal的问题,一直没搞懂,不知道跟这个是不是有关系?

不会有问题,你就放心用这个代码就行了。

谢谢。

你这情况和ThreadLocal无关。贴个使用ThreadLocal的SessionFactory,供参考。


import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.MappingException;

public class HibernateSession {

private static ThreadLocal currentThread = new ThreadLocal();

public static synchronized Session openSession() throws HibernateException {
Session s = (Session) currentThread.get();
if (s == null) {
Configuration conf = new Configuration().addClass(Person.class) ...; // 增加映射POJO
SessionFactory sf = conf.buildSessionFactory();
s = sf.openSession();
currentThread.set(s);
}
return s;
}

public static void closeSession() throws HibernateException {
Session s = (Session) currentThread.get();
currentThread.set(null);
if (s != null) s.close();
}
}