我有一个hibernate DAO,当试图访问一个包/集合的返回对象的成员时抛出一个“无法懒惰地初始化一个角色集合”异常。保持Hibernate会话通过注释失效? - 未能懒洋洋地初始化一个角色集合
我明白抛出异常的问题的范围。 Hibernate返回我的对象,并且对于任何集合,返回代理对象。在我的调用者中,当我去访问这些代理对象时,因为休眠会话已经过期,这个异常被抛出。
我想知道的是,如何使用注释保持会话从到期?可能吗?
举例来说,如果我的调用方法:
@RequestMapping("refresh.url")
public ModelAndView refresh(HttpServletRequest request, HttpServletResponse response, int id) throws Exception {
TestObject myObj = testObjDao.get(id);
// throws the exception
myObj.getCollection();
我将如何防止使用注解这个异常?我知道有一个解决办法是通过回调这伪代码可能看起来像延长Hibernate的Session:
@RequestMapping("refresh.url")
public ModelAndView refresh(HttpServletRequest request, HttpServletResponse response, int id) throws Exception {
session = get hibernate session...
session.doInSession(new SessionCallback() {
TestObject myObj = testObjDao.get(id);
// no longer throws the exception
myObj.getCollection();
});
但这似乎相当重复的有在我所有的功能需要访问集合。是不是有一种方法可以在那里简单地拍@Transactional注释并完成它?如在:
@RequestMapping("refresh.url")
@Transactional // this doesn't extend the session to this method?
public ModelAndView refresh(HttpServletRequest request, HttpServletResponse response, int id) throws Exception {
TestObject myObj = testObjDao.get(id);
// throws the exception
myObj.getCollection();
感谢您的帮助,向我解释这一点。