Hibernate的懒加载问题

来源:互联网 发布:mac office行高 编辑:程序博客网 时间:2024/04/29 00:53

简述: 当我们查询一个对象的时候,在默认情况下,返回的只是该对象的普通属性,当用户去使用对象属性时,才会向数据库发出再一次的查询.这种现象我们称为 lazy现象.

解决方法可以这样:

1.      显示初始化 Hibernate.initized(代理对象)。

2.      修改对象关系文件 lazy  改写 lazy=false。

3.      通过过滤器(web项目)openSessionInView。



前面两种就不解析了,现在讲讲openSessionView。说白了就是让session范围更大,即稍微延时关闭Session。这里再画个图体会下:




讲解下代码怎么操作。


先创建一个类继承HttpServlet实现filter接口,例如:public class MyFilterOnSessionView extends HttpServlet implements Filter。


然后在web.xml文件中配置

<servlet><description>This is the description of my J2EE component</description><display-name>This is the display name of my J2EE component</display-name><servlet-name>MyFilterOnSessionView</servlet-name><servlet-class>com.lmk.filter.MyFilterOnSessionView</servlet-class></servlet><servlet-mapping><servlet-name>MyFilterOnSessionView</servlet-name><url-pattern>/MyFilterOnSessionView</url-pattern></servlet-mapping>



最后把你平时对Hibernate中的Session打开和关闭代码放在doFilter方法中,例如:

@Overridepublic void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain arg2) throws IOException, ServletException {Session session = null;Transaction ts = null;try {    //打开Sessionsession = HibernateUtil.getCurrentSession();//开始事务ts = session.beginTransaction();// 让它兜一圈arg2.doFilter(arg0, arg1);// 提交事务ts.commit();} catch (Exception e) {throw new RuntimeException(e.getMessage());} finally {    //关闭SessionHibernateUtil.closeSession();}}




0 0