1

entity :

class A{
   private int id;
   @oneToMany(mappedBy = "a")
   private List<B> bList;
}
class B{
   private int id;
   @ManToOne
   private A a;
}

repository :

interfase BRepository{ 
   @Query("select b from B b where b.a.id = ?1")
   public List<B> getB(String id);
}

controller :

private BRepository b;
@RequestMapping("/b")
public Object getB(){
     return b.getB(1);
}

return JSON in an infinite loop .

Use the @JsonBackReference annotation on the class A, normal results :

   class A{
   private int id;
   @oneToMany(mappedBy = "a")
   @JsonBackReference  //this property is ignored
   private List<B> bList;
}

But when you query a class, the returned results not bList (using @JsonBackference), what can I do to return the bList properties?

1 Answer 1

1

I would suggest not to use circular references between your objects for the following reasons.

This generate a lot of issues and JSON generation is one of them.

•Circular class references create high coupling; both classes must be recompiled every time either of them is changed.

•Circular assembly references prevent static linking, because B depends on A but A cannot be assembled until B is complete.

•Circular object references can crash naïve recursive algorithms (such as serializers, visitors and pretty-printers) with stack overflows. The more advanced algorithms will have cycle detection and will merely fail with a more descriptive exception/error message.

•Circular object references also make dependency injection impossible, significantly reducing the testability of your system.

•Objects with a very large number of circular references are often God Objects. Even if they are not, they have a tendency to lead to Spaghetti Code.

•Circular entity references (especially in databases, but also in domain models) prevent the use of non-nullability constraints, which may eventually lead to data corruption or at least inconsistency.

•Circular references in general are simply confusing and drastically increase the cognitive load when attempting to understand how a program functions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.