Search code examples
javaspringspring-mvcspring-datafasterxml

Spring MVC / Spring Data data fetch recursion


I have an entity with one-to-many relationship (for ex. Person o->m Book). If I want to fetch a person with books in controller, it causes recursion. @JsonIgnore by FasterXML helps, but what if I want bidirectional fetch without recursion. For example fetch Person with Books and fetch Book with Persons?


Solution

  • Use @JsonBackReference

    class Person{
        @OneToMany(mappedBy="person",fetch = FetchType.EAGER)
        private List<Book> books; 
        ...
    }
    
    class Book { 
        @ManyToOne
        @JoinColumn(columnDefinition="integer", name = "person", nullable=false)
        @JsonBackReference
        private Person person;
        ...
    }