Zade Abderrahmane
Zade Abderrahmane

Reputation: 11

JSON Serialization Issue with Bidirectional OneToOne Relationship

I have two Java entities with a bi-directional One To One relationship between them: Sinistre and RapportTechnique. When I generate the JSON file to send to the front end, I encounter unwanted recursion.

Class Sinistre

@Data   
@Entity
@EqualsAndHashCode(callSuper = false)
@Table(name = "sinistre")
public class Sinistre extends Audit {

    @Column
    private String code;

    @Column
    private LocalDateTime dateIncident;

    @Column
    private double montantIndem;

    @ManyToOne
    @JoinColumn(name = "structure_id", referencedColumnName = "id")
    private Structure structure;

    @OneToOne(mappedBy = "sinistre")
    @JsonManagedReference
    private RapportTechnique rapportTechnique;
}

Classe RapportTechnique

@Data
@Entity
@EqualsAndHashCode(callSuper = false)
@Table(name = "rapportTech")
public class RapportTechnique extends Audit {
    @Column
    private String reference;

    @Column
    private String nature_Sinistre;

    @Column
    private String causes_Sinistre;

    @Column
    private String date_intervention;

    @OneToOne
    @JoinColumn(name = "sinistre_id")
    @JsonBackReference
    private Sinistre sinistre;
}

I tried the @JsonIgnore annotation, but it completely ignores the relationship in the JSON. I discovered the @JsonManagedReference and @JsonBackReference annotations, which solve the recursion but only in one direction. How can I maintain the bidirectional relationship while avoiding recursion when generating the JSON file for the 'Sinistre' entity, which contains a reference to 'RapportTechnique' and vice versa?

Upvotes: 0

Views: 266

Answers (2)

Kendy Alvarado
Kendy Alvarado

Reputation: 41

Choose one class as the principal and in the secondary class, fetch the object lazily using the @OneToOne(fetch = FetchType.LAZY) annotation. This ensures that the associated object is loaded lazily, improving performance by fetching it only when needed.

Upvotes: 0

Anton Kozub
Anton Kozub

Reputation: 618

You can use JsonIgnoreProperties:

@OneToOne(mappedBy = "sinistre")
@JsonIgnoreProperties("sinistre")
private RapportTechnique rapportTechnique;

and

@OneToOne
@JoinColumn(name = "sinistre_id")
@JsonIgnoreProperties("rapportTechnique")
private Sinistre sinistre;

Upvotes: 0

Related Questions