Spring中的Json错误
我尝试了这个:
@RequestMapping(method = RequestMethod.GET, value = "/getmainsubjects")
@ResponseBody
public JSONArray getMainSubjects( @RequestParam("id") int id) {
List <Mainsubjects> mains = database.getMainSubjects(id, Localization.getLanguage());
JSONArray json = JSONArray.fromObject(mains);
return json;
}
调用 getmainsubjects.html?id=1 时出现错误:
net.sf.json.JSONException:org.hibernate.LazyInitializationException:无法延迟初始化角色集合:fi.utu.tuha.domain.Mainsubjects.aiForms,没有会话或会话已关闭
如何修复?
I tried this:
@RequestMapping(method = RequestMethod.GET, value = "/getmainsubjects")
@ResponseBody
public JSONArray getMainSubjects( @RequestParam("id") int id) {
List <Mainsubjects> mains = database.getMainSubjects(id, Localization.getLanguage());
JSONArray json = JSONArray.fromObject(mains);
return json;
}
When calling getmainsubjects.html?id=1 I get the error:
net.sf.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: fi.utu.tuha.domain.Mainsubjects.aiForms, no session or session was closed
How to fix?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是,
你的模型对象 Mainsubjects 有一些关联(由 OneToMany、ManyToOne 等构建)、列表(PersistentBags)、集合或类似的东西(集合),它们是延迟初始化的。这意味着,在初始化结果集之后,Mainsubjects 并不指向实际的集合对象,而是指向代理。在渲染、访问此集合时,hibernate 尝试使用代理从数据库获取值。但此时还没有开放的会话。因此你会得到这个例外。
您可以将获取策略设置为 EAGER(如果您使用注释),如下所示:
@OneToMany(fetch=FetchType.EAGER)
在此方法中,您必须注意,您不能允许多个 PersistedBag 急切地初始化。
或者您可以使用 OpenSessionInView 模式,这是一个 servlet 过滤器,在控制器处理您的请求之前打开一个新会话,并在 Web 应用程序响应之前关闭:
The problem is,
your model object Mainsubjects had some associations (built by OneToMany, ManyToOne, etc.), Lists (PersistentBags), Sets or something (Collection) like this which're initialized lazily. It means, after initialization of result set, Mainsubjects doesn't point to an actual collection object, instead proxies. While rendering, accessing this collections, hibernate tries to get the values from Database using proxies. But at this point there's no session open. For that reason you get this exception.
You can either set your fetching strategy to EAGER (if you use annotations) like this:
@OneToMany(fetch=FetchType.EAGER)
In this method you must be aware, that you can not allow more than one PersistentBag initialized eagerly.
or you can use OpenSessionInView pattern, which's a servlet filter opens a new session before your request's handeled by controller, and closes before your web application responses: