我開始使用Hibernate與Struts 2相對簡單的Web項目。出於性能原因,我知道建議儘量減少創建Hibernate配置和SessionFactory對象的次數。存儲與Struts的Hibernate SessionFactory
任何人都可以提供一些關於這是否是一種好方法或者是否有更好的方法?我基於這個代碼example I found here。
該方法是在ServletContextListener的contextInitialized方法中創建SessionFactory並將其存儲在ServletContext中。
我注意到這個例子似乎並沒有關閉SessionFactory,所以我在contextDestroyed中添加了一些代碼。這是必要的嗎?
非常感謝任何輸入。如果你能提出更好的例子,我會很高興看到他們。我還看到了一些Struts的「Full Hibernate Plugin」參考。這是一種常用和更好的方法嗎?
FWIW,我使用Eclipse和與MySQL部署到Tomcat
public class HibernateListener implements ServletContextListener {
private Configuration config;
private SessionFactory sessionFactory;
private String path = "/hibernate.cfg.xml";
public static final String KEY_NAME = HibernateListener.class.getName();
@Override
public void contextDestroyed(ServletContextEvent arg0) {
if (sessionFactory != null) {
sessionFactory.close();
}
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
try {
URL url = HibernateListener.class.getResource(path);
config = new Configuration().configure(url);
sessionFactory = config.buildSessionFactory();
// save the Hibernate session factory into serlvet context
arg0.getServletContext().setAttribute(KEY_NAME, sessionFactory);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
這裏就是我添加到web.xml
<listener>
<listener-class>insert.package.name.here.HibernateListener</listener-class>
</listener>
感謝您的回覆。我很感激。我會檢查谷歌Guice。我以前沒聽說過。 – Justin 2011-04-17 01:11:47