I am using Hibernate 4.1 and Spring 3.1.
Consider the following User class having references to other object including self. All the hibernate mappings I have defined are LAZY so will load the reference objects only when I use them in the jsp or code else where.
class User {
private User createdBy;
private Department department;
private Project project;
.....
.....
}
The problem is when I want to return a JSON representation where it uses reflection to do it and there by does a deep serialization. Below is my controller code.
@ResponseBody
public User getUser(int id) {
User user = [fetch user from service];
return user;
}
Since I have self reference also it goes into infinite loop.
What is the solution to get away with this problem? I know that I need to use DTO pattern where I return a UserDTO instead but how many such methods I create. For example, at one place I need just the basic User attributes, at other place I need User and its Department, at other place I need User with Department and Project.
How many such methods I would need to expose. Is there any other way to resolve this?