session关闭以后,如果还想用相关的对象,比如在页面中进行输出,但又不至于出现session已关闭的错误而导致无法获取对象的信息,本文提供三种解决方式:
1:第一次获得该对象的时候用get而不用load,因get不支持懒加载,在get该对象的同时会想数据库发出sql语句,取出该对象的相应信息放入缓存中,下次即使session已经关闭,因缓存中有相应的数据,查找该对象时会首先从缓存中查询,直接拿来用就ok了
2:可以把相应对象的lazy设为false,这样在load该对象的同时就会发sql语句取出该对象放到缓存中,以后再用可以直接从缓存中取,从而也避免了该异常
3:采用openSessionInView 该方式是通过延长session的时间方式来解决的,可以写一个filter或者inteceptor,下面以filter为例
private SessionFactory sf;
//filter -- >
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
// sf.getCurrentSession();//获得和当前线程绑定的session
sf.getCurrentSession().beginTransaction();
chain.doFilter(request, response);
sf.getCurrentSession().getTransaction().commit();
} catch (StaleObjectStateException staleEx) {
throw staleEx;
} catch (Throwable ex) {
ex.printStackTrace();
try {
if (sf.getCurrentSession().getTransaction().isActive()) {
sf.getCurrentSession().getTransaction().rollback();
}
} catch (Throwable rbEx) {
}
throw new ServletException(ex);
}
}
public void init(FilterConfig filterConfig) throws ServletException {
sf = HibernateSessionFactory.getSessionFactory();
}
public void destroy() {
}