映射JsonMappingException的多对多:无限递归(StackOverflowError)

时间:2017-09-08 17:39:15

标签: java jpa spring-boot

我知道这是一个重复的问题。我已经多次完成了这种类型的实现。不知道为什么这次不工作。
非常标准的实施 我知道这是一个重复的问题。我已经多次完成了这种类型的实现。不知道为什么这次不工作。
非常标准的实施

public class Car implements BaseResponse {

    @Id
    @SequenceGenerator(name = "car_generator", sequenceName = "car_sequence", allocationSize = 1)
    @GeneratedValue(generator = "car_generator")
    private Long id;
    @NotNull
    private String name;
    @NotNull
    private String description;

    @ManyToMany(fetch = FetchType.LAZY, mappedBy="cars")
    private Set<part> parts;
}

@JsonIgnoreProperties({"cars"})
public class Part implements BaseResponse {

    @Id
    @SequenceGenerator(name = "part_generator", sequenceName = "part_sequence", allocationSize = 1)
    @GeneratedValue(generator = "part_generator")
    private Long id;

    private String name;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
              name = "car_part",
              joinColumns = @JoinColumn(name = "part_id", referencedColumnName = "id"),
              inverseJoinColumns = @JoinColumn(name = "car_id", referencedColumnName = "id"))
    private Set<car> cars;
}

create table if not exists parts
(
    id BIGINT,
    name varchar,
    criteria varchar,
    customers_count int,
    primary key(id)
);

create table if not exists car_part
(
    car_id bigint,
    part_id bigint
);

我一直得到的错误是

Could not write content: Infinite recursion (StackOverflowError) (through reference chain: java.util.ArrayList[0]->com.saylent.domain.car["parts"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: java.util.ArrayList[0]->com.saylent.domain.car["parts"])

1 个答案:

答案 0 :(得分:3)

@JsonManagedReference@JsonBackReference旨在使用父字段和子字段之间的双向链接。

@ManyToMany(fetch = FetchType.LAZY, mappedBy="cars")
@JsonBackReference
private Set<part> parts;


@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
          name = "car_part",
          joinColumns = @JoinColumn(name = "part_id", referencedColumnName = "id"),
          inverseJoinColumns = @JoinColumn(name = "car_id", referencedColumnName = "id"))
@JsonManagedReference
private Set<car> cars;