When trying to convert a JPA object that has a bi-directional association into JSON, I keep getting
org.codehaus.jackson.map.JsonMappingException: Infinite
I had this problem, but I didn't want to use annotation in my entities, so I solved by creating a constructor for my class, this constructor must not have a reference back to the entities who references this entity. Let's say this scenario.
public class A{
private int id;
private String code;
private String name;
private List bs;
}
public class B{
private int id;
private String code;
private String name;
private A a;
}
If you try to send to the view the class B
or A
with @ResponseBody
it may cause an infinite loop. You can write a constructor in your class and create a query with your entityManager
like this.
"select new A(id, code, name) from A"
This is the class with the constructor.
public class A{
private int id;
private String code;
private String name;
private List bs;
public A(){
}
public A(int id, String code, String name){
this.id = id;
this.code = code;
this.name = name;
}
}
However, there are some constrictions about this solution, as you can see, in the constructor I did not make a reference to List bs this is because Hibernate does not allow it, at least in version 3.6.10.Final, so when I need to show both entities in a view I do the following.
public A getAById(int id); //THE A id
public List getBsByAId(int idA); //the A id.
The other problem with this solution, is that if you add or remove a property you must update your constructor and all your queries.