最近我們學到的Hibernate中,有個對房屋信息的查詢功能。其中頁面的一句代碼如下:
${house.street.district.name}區${house.street.name},${house.floorage}平米<br /> 聯繫方式:${house.contact}
以上寫法用EL顯示房屋的信息,但我們的DAO用Hibernate實現的時候,幾個相關的對象都要把lazy設置成false,不然就會出現會話已經關閉的錯誤。以下是House.hbm.xml原來的寫法:
<many-to-one name="users" class="org.newboy.entity.Users" fetch="join" lazy="false">
<column name="USER_ID" precision="7" scale="0" />
</many-to-one>
<many-to-one name="houseType" class="org.newboy.entity.HouseType" fetch="select" lazy="false">
<column name="TYPE_ID" precision="4" scale="0" />
</many-to-one>
<many-to-one name="street" class="org.newboy.entity.Street" fetch="join" lazy="false">
<column name="STREET_ID" precision="6" scale="0" />
</many-to-one>
因爲在訪問到house.street的時候,Hibernate還會再去查一次數據庫,而如果我們的DAO中的代碼如下:
@SuppressWarnings("unchecked")
public List<House> getAllHouses() {
Session session = super.getSession();
List<House> houses = null;
try {
houses = session.createQuery("from House").list();
} finally {
session.close();
}
return houses;
}
會話已經關閉,就會出現會話關閉的錯誤。當然還有一種做法就是不關閉會話,不過這不是一種解決的辦法。
雖然以後我們會學到Spring有更好的解決方法,但今天如果只用Hibernate的話,我們自己有沒有辦法去解決這個問題,就是讓會話在請求結束後才關閉。這樣也就不用把lazy設置成false了。於是就有了下面的過濾器的實現:
package org.newboy.servlet;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.newboy.utils.HibernateUtils;
/**
* 用於進行Hibernate事務處理的Servlet過濾器
*
* @author LiuBo
*/
public class HibernateFilter implements Filter {
private static Logger log = Logger.getLogger(HibernateFilter.class);
/**
* 過濾器的主要方法 用於實現Hibernate事務的開始和提交
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
Session session = HibernateUtils.getSession();
Transaction tx = session.beginTransaction();
try {
// 開始一個新的事務
log.info("Starting a database transaction");
tx.begin();
log.info("Request Path:\t" + ((HttpServletRequest) request).getServletPath());
// Call the next filter (continue request processing)
chain.doFilter(request, response);
// 提交事務
log.info("Committing the database transaction");
tx.commit();
} catch (Throwable ex) {
ex.printStackTrace();
try {
// 回滾事務
log.info("Trying to rollback database transaction after exception");
tx.rollback();
} catch (Throwable rbEx) {
log.error("Could not rollback transaction after exception!", rbEx);
}
// 拋出異常
throw new ServletException(ex);
} finally {
log.info("session closed");
HibernateUtils.closeSession();
}
}
/**
* Servlet過濾器的初始化方法 可以讀取配置文件中設置的配置參數
*/
public void init(FilterConfig filterConfig) throws ServletException {
}
/**
* Servlet的銷燬方法 用於釋放過濾器所申請的資源
*/
public void destroy() {
}
}
<filter>
<description>事務的過濾器</description>
<filter-name>HibernateFilter</filter-name>
<filter-class>org.newboy.servlet.HibernateFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
這樣我們的DAO就可以這樣寫:
@SuppressWarnings("unchecked")
public List<House> getAllHouses() {
Session session = HibernateUtils.getSession();
List<House> houses = session.createQuery("from House").list();
return houses;
}
不用關閉會話,而House.hbm.xml就變成:
<many-to-one name="users" class="org.newboy.entity.Users">
<column name="USER_ID" precision="7" scale="0" />
</many-to-one>
<many-to-one name="houseType" class="org.newboy.entity.HouseType">
<column name="TYPE_ID" precision="4" scale="0" />
</many-to-one>
<many-to-one name="street" class="org.newboy.entity.Street">
<column name="STREET_ID" precision="6" scale="0" />
</many-to-one>
沒有了lazy那項。
其中HibernateUtils的代碼基本上是MyEclipse自動產生的。只是我把它漢化了。呵呵:
package org.newboy.utils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
* 配置Hibernate工具,對會話工廠和會話進行操作
*/
public class HibernateUtils {
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("會話工廠創建失敗");
e.printStackTrace();
}
}
/*
* 私有的構造方法
*/
private HibernateUtils() {
}
/**
* 得到一個線程安全的實例
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession() : null;
threadLocal.set(session);
}
return session;
}
/**
* 重新建立會話工廠
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("會話工廠創建失敗");
e.printStackTrace();
}
}
/**
* 關閉單個會話實例.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* 返回會話工廠實例
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* 設置配置文件
*/
public static void setConfigFile(String configFile) {
HibernateUtils.configFile = configFile;
sessionFactory = null;
}
/**
* 返回配置對象
*/
public static Configuration getConfiguration() {
return configuration;
}
}
這樣每次用戶請求就會打開會話和事務,請求結束就提交事務,並關閉會話。解決了上面的問題。