skip to Main Content

I have two Java entities with a bidirectional OneToOne relationship between them: ‘Sinistre’ and ‘RapportTechnique.’ When I generate the JSON file to send to the frontend, I encounter unwanted recursion.## Heading ##

Classe 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?

2

Answers


  1. You can use JsonIgnoreProperties:

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

    and

    @OneToOne
    @JoinColumn(name = "sinistre_id")
    @JsonIgnoreProperties("rapportTechnique")
    private Sinistre sinistre;
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search