Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular reference in entity JPA with Jackson and Spring Boot

I have two web services: "Proprietario" and "Veiculo", the "Proprietario" contains a list of "Veiculo" and "Veiculo" contains a "Proprietario".

The problem is that when I make a request calling the findAll method of "Proprietario", when trying to serialize, Jackson goes into infinite loop throwing exception. The same happens when I try to call the findAll method of "Veiculo".

I would like it when I call you to call the findAll of the "Veiculo", bring along the "Proprietario", but do not bring the "Veiculo" list inside the "Proprietario". The opposite of when I call the findAll method of "Proprietario", I'd like to bring the "Veiculo" list, but do not bring the "Proprietario" into the "Veiculo".

I tried to use some Jackson annotations, but none solves the conflict on both sides.

@Getter
@Setter
@Entity
@EqualsAndHashCode(of = "id")
public class Veiculo {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    @Column(length = 10)
    private String placa;

    @Column(nullable = false)
    private Integer ano;

    @ManyToOne
    @JoinColumn
    private Proprietario proprietario;
}


@Getter
@Setter
@Entity
@EqualsAndHashCode(of = "id")
public class Veiculo {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    @Column(length = 10)
    private String placa;

    @Column(nullable = false)
    private Integer ano;

    @ManyToOne
    @JoinColumn
    private Proprietario proprietario;
}
like image 997
Felix Ricardo Gilioli Avatar asked Oct 28 '25 04:10

Felix Ricardo Gilioli


1 Answers

Try using these two annotations @JsonManagedReference and @JsonBackReference

see http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion

like image 87
Selvam M Avatar answered Oct 29 '25 18:10

Selvam M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!