I have a hibernate DAO that is throwing a “failed to lazily initialize a collection of role” Exception when trying to access a member of the returned object that is a bag/Collection.
I understand the scope of the problem throwing the exception. Hibernate returns my object, and for any Collections, returns proxy objects. In my caller, when I go to access those proxy objects, because the hibernate session has expired, this exception is thrown.
What I want to know is, how can I keep the session from expiring using annotations? Is it possible?
For instance if my calling method is:
@RequestMapping("refresh.url")
public ModelAndView refresh(HttpServletRequest request, HttpServletResponse response, int id) throws Exception {
TestObject myObj = testObjDao.get(id);
// throws the exception
myObj.getCollection();
How would I prevent this exception using annotations? I know one solution would be to extend the hibernate session via a callback which in pseudocode might look something like:
@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();
});
but this seems rather repetitive to have in all of my functions that need to access collections. isn’t there a way to simply slap an @Transactional annotation on there and be done with it? as in:
@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();
thanks for your help in explaining this to me.
The solution I used was to use the @LazyCollection annotation on the collection in the DAO.