简体   繁体   中英

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

Try using these two annotations @JsonManagedReference and @JsonBackReference

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM