3

I know it is a duplicate question. I have done this type of implementation many times. Not sure why is it not working this time.
very standard implementation I know it is a duplicate question. I have done this type of implementation many times. Not sure why is it not working this time.
very standard implementation

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

The error I keep getting is

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"])
Himanshu Yadav
  • 13,315
  • 46
  • 162
  • 291

1 Answers1

4

@JsonManagedReference and @JsonBackReference are designed to use two-way linkage between parent and child fields.

@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;
fkrsc
  • 151
  • 2
  • 5