0

I know this is a classic problem, but somehow I can't figure how to solve this issue.

So I have a OneToMany relationship between two entities, A and B.

In A I have the following method:

@OneToMany(cascade=CascadeType.ALL, mappedBy = "a")
public Set<B> getBList() {
    return this.bList;
}

Somewhere in a controller, in a handler method I have something like

@RequestMapping("/")
public String method(Model model){
    A a = aDAO.findById(1);
    for(B b : a.getBList()){
        System.out.println(b);
    }   
    model.addAttribute("a",a);
}

and in the jsp page I have the following EL:

${a.bList}

In the handler method, everything works fine, the list of B objects that the A object has is displayed properly in the console.

But at the rendering of the jsp page, the LazyInitializationException appears:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.entities.A.bList, no session or session was closed

I understand this exception usually appears (correct me if I'm wrong) because the session from which the A is obtained has been closed in the meantime. But in the findById(Long id) method from the DAO class I don't close the session. And i guess that is the reason why the printing in the handler method works. But then why the exception caused by the EL? Does the session get closed at the interpretation of the JSP page?

Also, what can be done to be able to access the list in EL?

Catalin Florea
  • 227
  • 3
  • 12

1 Answers1

0

As you mentioned , It is issue of hibernate session as it required to execute method within hibernate transaction you need to write @Transactional Attribute to your dao method.

Jekin Kalariya
  • 3,475
  • 2
  • 20
  • 32