Felix Ricardo Gilioli
Felix Ricardo Gilioli

Reputation: 199

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;
}

Upvotes: 3

Views: 13504

Answers (1)

Selvam M
Selvam M

Reputation: 530

Try using these two annotations @JsonManagedReference and @JsonBackReference

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

Upvotes: 7

Related Questions