使用 Spring 整合 Hibernate, 在懶加載的情況下, 有時候需要在 JSP/View 層顯示數據, 這時候就要用到Spring內置的: OpenSessionInViewFilter, 一般來說配置如下(web.xml):
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param><!-- 和 spring 中的sesssionfactory ID 一致 -->
</filter>
<filter-mapping><filter-name>hibernateFilter</filter-name><url-pattern>*.do</url-pattern><!-- *.jsp, *.do--></filter-mapping>
不過, 這時候又會導致更新數據時拋出如下異常:
Write
operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL):
Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly'
marker from transaction definition.
這時候再去網上找解決方案, 會有人說: 把參數 singleSession改為false, 就行了. 不過, 改完后, 估計不久就會遇到另一個郁悶的異常:
org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
這下完了, 兩個方案都不行, 到底怎么辦? 還好, 在http://xuliangyong.javaeye.com/blog/144818的主頁上, 給了一個方案, 就是改寫 OpenSessionInViewFilter 的代碼, 非常感謝, 下面給出的就是最終方案:
web.xml
<
filter-name
>hibernateFilter</filter-name>
<
filter-class
> org.springframework.orm.hibernate3.support.OurOpenSessionInViewFilter </filter-class>
OurOpenSessionInViewFilter.java 代碼:
package org.springframework.orm.hibernate3.support;
import org.hibernate.*;
/** * 單session模式下, 默認會發生無法提交的錯誤: * Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition. * 需要設置FlushMode并刷新session. * 參考: http://xuliangyong.javaeye.com/blog/144818 * @author 劉長炯 */publicclass OurOpenSessionInViewFilter extends OpenSessionInViewFilter {
public OurOpenSessionInViewFilter() {
super.setFlushMode(FlushMode.AUTO);
}
protectedvoid closeSession(Session session, SessionFactory sessionFactory) {
session.flush();
try {
session.getTransaction().commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block//e.printStackTrace();
}
super.closeSession(session, sessionFactory);
}
}
如果各位有更好的解決方案, 歡迎討論哦!!!
題外話:
感覺 Spring + Hibernate 的健壯性還是不夠啊! 容易拋異常, 這是事實, 也許這是開源軟件的通病吧.