1

I have 3 entity classes with relations as below:

class SocietyData {

  @OneToMany(mappedBy = "societyData")
  private List<SubsectionData> subsectionDataList = new ArrayList<>();
}


class SubsectionData {
  @ManyToOne(cascade = CascadeType.ALL) 
  @JoinColumn(name = "society_id", nullable = false)
  private SocietyData societyData;
  
  @OneToMany(mappedBy = "subsectionData")
  private List<BasementData> basementDataList = new ArrayList<>();
}

class BasementData {
  
  @ManyToOne(cascade = CascadeType.ALL)
  @JoinColumn(name = "subsection_id", nullable = false)
  private SubsectionData subsectionData;
}

I am trying to fetch society data information by using entity graph:

@Repository
public interface SocietyRepo extends JpaRepository<SocietyData, Long> {


    @EntityGraph(attributePaths = {"subsectionDataList", "subsectionDataList.basementDataList"})
    Optional<SocietyData> findById(long id);
  
}

I am not getting proper society data object and getting cant parse json exception after taking so long time sometimes!

How to solve this?

Thanks in Advance.

Forece85
  • 428
  • 1
  • 6
  • 22
  • 1
    You have a cyclic dependency in your JPA entities leading to a stackoverflow when generating JSON. You need to tell jackson where to stop or what not to include in the response. – M. Deinum Apr 13 '22 at 12:30
  • I tried adding `@JsonIgnore` on `@OneToMany` fields (i.e., subsectionDataList & basementDataList). In this case even though I specified `@EntityGraph`, still I am not getting nested entity details in response. – Forece85 Apr 13 '22 at 12:42
  • placing `@JsonIgnore` on `@ManyToOne` side (i.e., subsectionData, societyData) worked. Is there any ideal way to solve this other than this way? – Forece85 Apr 13 '22 at 13:19
  • You need to instruct Jackson to stop somewhere due to all those cyclic relationships in your code. If you don't it will keep looping. If you don't you need to construct a DTO or Projection which doesn't have those cyclic relationships. – M. Deinum Apr 13 '22 at 13:34

0 Answers0