How to avoir infinite recursion using bidirectionnal OneToMany relationships, and get the informations from both sides?

121 views Asked by At

Let's say that an author have written many books, and also many books have only one author.

So that it is a bidirectional relationship.

When you try to serialize it, it becomes an infinite loop of books and authors like this :

{
    "id": 1,
    "name": "1984",
    "author": {
        "id": 1,
        "name": "George Orwell",
        "books": [
            {
                "id": 1,
                "name": "1984",
                "author": {
                    "id": 1,
                    "name": "George Orwell",
                    "books": [
                        {
                            "id": 1,
                            "name": "1984",
                            "author": {
                ...etc.

Those two annotations (@JsonManagedReference and @JsonBackReference) help us to break this loop :

@Entity
public class Book {
    
    @ManyToOne
    @JoinColumn(name = "author_id")
    @JsonManagedReference
    private Author author;

}

@Entity
public class Author extends AbstractEntity {
    
    @OneToMany(mappedBy = "author", fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
//  @JsonIgnore
    @JsonBackReference
    private Set<Book> books;

}

But with this solution you can access to the books with their proper author

{
    "id": 1,
    "name": "1984",
    "author": {
        "id": 1,
        "name": "George Orwell"
    }
}

, but you can access to the authors with their books :

{
    "id": 1,
    "name": "George Orwell"
}

Does someone already did fix this problem ? Or it's just the way it is to access the complete information from only one side ?

Thank you for your help

Joss

0

There are 0 answers