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?
The problem is that you have a circular reference and your JSON encoder is not handling it. So, you need to handle it manually.
Creating a DTO as you commented would help. You can implement a Helper with one method for each level of decoding you need.
You could use
BeanUtilsto copy each property from one bean to the other.Another solution (a bit more conceptual) would be:
Implement a kind of decorator for each boundary method and apply dozer over the result. An example you could take here
The Decoration occurs more or less like this: