I have an Parent object that contains a list of Child objects. When I fetch a list of these Parents (to display in a grid) I do NOT want all the Child objects - that just wastes time and memory. However, when I fetch a single Parent (to display all details of the parent on a different page) I DO want a list of its Children.
class Parent {
String name;
List<Child> children;
}
class Child {
String name;
Date birthDate;
}
So I set up lazy-fetch on Children so that by default the Children are not returned (when getting a list), but I can set FetchMode to JOIN to return the full object (Parent + Children) for a single Parent when I want it. This works fine.
However, for my action class that queries these two sets of data to 'return' it to my JSP screens, I use Gson.toJson(object) to format it. This throws a LazyInitializationException because its trying to fetch the Children. I don't WANT the children to be fetched when I don't need that data.
So this brings up some questions on how to 'fix' this situation :
1) Can I tell/configure Gson to NOT fetch missing lazy-fetched children?
2) If not, is there an alternative Json formatter to Gson that will respect hibernate lazy-fetch?
3) Is there another way for my action class to return or make accessible the Java bean objects that are fetched from a DB to the JSPs so that the data can be used to fill in fields and grids, other than using json format?