我的实体类Deptment 中 @OneToMany(mappedBy="deptment",cascade=CascadeType.ALL,fetch=FetchType.LAZY) public Set<Employee> getEmployees() { return employees; } 在dao层中 public List<Deptment> queryDeptList() { List<Deptment> deptList = this.hibernateTemplate.find("from Deptment"); return deptList; } 为什么在jsp中读取DeptmentList会报错:failed to lazily initialize a collection of role: model.Deptment.employees, no session or session was closed; 前台jsp中我没有读取Deptment中的employees中数据啊。 在线等。。。求高手解答
提问者采纳
这个是很典型的有懒加载引起的问题,你懒加载的时候只加载了了department的基本信息,而部门下的员工信息是懒加载的,当你要去用department下的employee信息,那么又会去加载。而此时你的session已经关闭了,所以才会报nosession错。 解决办法:在你的web.xml中添加下面的配置 <!-- 把session的关闭延迟到jsp页面显示之后,在配在struts2上面。--> <filter> <filter-name>OpenSessionInView</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>OpenSessionInView</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
追问:
可是我前台没有读取集合employees啊,只是读取了部门的普通信息。。
追答:
你报错的信息, model.Deptment.employees, 这个说明你在取employees ,你仔细看看自己的代码,可能哪里隐藏的在取employees的信息。
-
2:知识扩展
-
本人遇到的问题如下:
-
首先定义了hibernate实体对象Resource:
-
接着需要查询数据库中的Resource数据时,调用find查询
-
注意,查询可以查询出来,不会保存,但是转化为JSON的时候,报错。报错截图:
-
同样是hibernate懒加载引起的错误。
-
解决办法如下:(原理,将list里面的用到属性一个一个取出来,组合成JSON字符串)
-
JSONObject datas = new JSONObject();
JSONArray items = new JSONArray();
List<Object[]> list = this.find(hql);
f(list!=null&&list.size()>0){
for(int i=0;i<list.size();i++){
Object[] obj = list.get(i);
JSONObject da = new JSONObject();
da.put("shname",obj[0]);
da.put("shfzr",obj[1]);
da.put("shadd",obj[2]);
da.put("shtype",obj[3]);
items.add(da);
}
}
datas.put("rows", items);
return datas;