Issue
I'm trying to conditionally @JsonIgnore
some fields from an entity if they're serialized from an other entity's collection (many to one).
I've tried to add @JsonIgnoreProperties
to the collection but as I understand that annotation is not for this purpose.
class A {
//some fields
@ManyToOne private B b; //if only A is requested, this should NOT be ignored
}
class B {
//some fields
@OneToMany
@IgnorePrivateBInAToAvoidStackOverflow
private Set<A> collectionOfAs;
}
Is there any way to achieve this behavior?
Solution
To avoid circular reference Infinite recursion ( stackoverflow error ) you have to annotate calss with @JsonIdentityInfo
So you class looks like :
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
class A {
//some fields
//Integer id;
@OneToMany private B b; //if only A is requested, this should NOT be ignored
}
Same thing for class B to bidirectional use :
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
class B {
//some fields
@ManyToOne
@IgnorePrivateBInAToAvoidStackOverflow
private Set<A> collectionOfAs;
}
be aware that the property
refers to your unique field name ( set to id
in this example )
for more reading see this article
Answered By - Spring
Answer Checked By - Gilberto Lyons (JavaFixing Admin)