Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA2/Hibernate - Stop lazy loading?

I'm having a problem where JPA is trying to lazily load my data when I don't want it to. Essentially what is happening is I'm using a Service to retrieve some data, and when I go to parse that data into JSON, the JSON library is triggering hibernate to try and lazily load the data. Is there any way to stop this? I've given an example below.

// Web Controller method
public String getEmployeesByQuery(String query) {

    Gson gson = new Gson();
    List<Employee> employees = employeeService.findEmployeesByQuery(query);

    // Here is where the problem is occurring - the gson.toJSON() method is (I imagine)
    // using my getters to format the JSON output, which is triggering hibernate to
    // try and lazily load my data...
    return gson.toJSON(employees);
}

Is it possible to set JPA/hibernate to not try and lazily load the data?

UPDATE: I realize that you can use FetchType.EAGER - but what if I don't want to eager load that data? I just want to stop hibernate from trying to retrieve more data - I already have the data I want. Right now whenever I try and access a get() method hibernate will throw a "no session or session is closed" error, which makes sense because my transaction was already committed from my service.

Thanks!

like image 204
Brian DiCasa Avatar asked Jan 26 '11 14:01

Brian DiCasa


1 Answers

There are several options:

  • If you always need to load your collection eagerly, you can specify fetch = FetchType.EAGER in your mapping, as suggested in other answers.

  • Otherwise you can enable eager fetching for particular query:

    • By using JOIN FETCH clause in HQL/JPQL query:

      SELECT e FROM Employee e JOIN FETCH e.children WHERE ...
      
    • By using fetch profiles (in JPA you can access Hibernate Session via em.unwrap(Session.class))
like image 81
axtavt Avatar answered Nov 10 '22 05:11

axtavt