HibernateUtil類(運算元據源 session 的管理)

xuniji123發表於2007-01-01
public class HibernateUtil {

private static Log log=LogFactory.getLog(HibernateUtil.class);

private static final SessionFactory sessionFactory;

static {
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
log.error("Initial SessionFactory creation failed.",ex);
throw new ExceptionInInitializerError(ex);
}
}

public static final ThreadLocal session=new ThreadLocal();

//得到session
public static Session Session() throws HibernateException {
Session s=(Session)session.get();
//Open a new Session, if this Thread has none yet
if (s==null) {
s=sessionFactory.openSession();
session.set(s);
}
return s;
}

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

}
[@more@]作者: louis850324 發表日期: 2006-12-30 16:40 文章屬性: 原創

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/8271432/viewspace-887887/,如需轉載,請註明出處,否則將追究法律責任。

相關文章