Could not write JSON: Infinite recursion (StackOverflowError)]

65 Views Asked by At

I am not getting "parent" field in response. If I remove @JsonBackReference annotation, the recursion will begin. I need to get parent object 1 time without recursion.

@Getter
@Setter
@ToString(callSuper = true)
@Entity(name = "organizations")
public class Organization
extends BaseEntity {

    /**
     * The parent organization, if applicable.
     */
    @ManyToOne
    @JoinColumn(name = "parent_id", referencedColumnName = "id")
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonBackReference
    private Organization parent;

    /**
     * The type of the organization.
     */
    @ManyToOne
    @JoinColumn(name = "organization_type_id", referencedColumnName = "id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @NotNull(message = "organizationType" + AppConstant.NOT_NULL_MESSAGE)
    private OrganizationType organizationType;

    /**
     * The ID of the associated address for this organization.
     */
    @Column(name = "address_id", nullable = false)
    @NotNull(message = "addressId" + AppConstant.NOT_NULL_MESSAGE)
    @Min(value = AppConstant.MIN_ID_VALUE, message = "addressId" + AppConstant.MIN_ID_MESSAGE)
    private Integer addressId;

    /**
     * The name of the organization.
     */
    @Column(name = "name", nullable = false)
    @NotNull(message = "name" + AppConstant.NOT_NULL_MESSAGE)
    @NotEmpty(message = "name" + AppConstant.NOT_EMPTY_MESSAGE)
    @Size(max = AppConstant.MAX_STRING_FIELD_LENGTH, message = "name" + AppConstant.STRING_FIELD_SIZE_MESSAGE)
    private String name;

    /**
     * The phone number associated with this organization.
     */
    @Column(name = "phone_number")
    @Size(max = AppConstant.MAX_STRING_FIELD_LENGTH, message = "phoneNumber" + AppConstant.STRING_FIELD_SIZE_MESSAGE)
    private String phoneNumber;

    @OneToMany(mappedBy = "organization", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonManagedReference("organization-organizationApps")
    private List<OrganizationApp> organizationApps;
}

I have tried @JsonIdentityInfo, @JsonManagedReference, @JsonBackReference. In @JsonIdentityInfo it is returning me the IDs after returning single object 1 time, and not putting it in node tree properly.

1

There are 1 best solutions below

0
On

In my opinion, in a self-referencing relationship, using @JsonIdentityInfo to obtain the ID values seems to be the best approach.