Spring JPA Self Reference Issue

Viewed 469

I created a table, Category in Postgres which holds both parent and child categories and references to itself (it's a self join table)

The table comprises of following columns: id, parent_id, start_date, end_date, status I also have one row for root parent whose id = 0. So, any first level categories have root as its parent.

Example: Apparel > Women. Here Apparel(id=1) is a first level category whose parent_id = 0. Women is another category whose parent_id = 1.

I am using Spring JpaRepository findAll on my table and this is leading to infinite recursion.

POJO

@Table(name = "ofr_category")
@Getter
@Setter
@NoArgsConstructor
public class Category {
  @Id
  @Column(name = "cat_id", updatable = true, unique = true, nullable = false)
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CATEGORY_SEQ")
  @SequenceGenerator(sequenceName = "CATEGORY_ID_SEQ", allocationSize = 1, name = "CATEGORY_SEQ")
  private Long id;

  @Column(name = "cat_name")
  private String name;

  @Column(name = "cat_status")
  private String status;

  @Column(name = "start_date")
  private LocalDate startDate;

  @Column(name = "end_date")
  private  LocalDate endDate;

  @Column(name = "parent_id")
  private Long parentId;

  @JsonBackReference
  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "parent_id", insertable = false, updatable = false)
  private Category parentCategory;

  @JsonManagedReference
  @OneToMany(fetch = FetchType.EAGER, mappedBy = "parentCategory")
  private List<Category> childCategories;

  public Category getParentCategory(){
    return parentCategory;
  }

 }

Exception seen "Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Direct self-reference leading to cycle (through reference chain: java.util.ArrayList[0]->com.test.category.dataobject.Category[\"parentCategory\"]->com.test.category.dataobject.Category[\"parentCategory\"]->com.test.category.dataobject.Category[\"parentCategory\"])",

1 Answers

Maybe you can have a look into @JsonIdentityInfo, which solved a similar problem for me. You can check if this basic annotation works for you.:

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Category {
...
}
Related