2

i have many to many relationship between book and author, i have 3 tables: author, book and author_book.

@Entity()
@Table(name = "author")
@NamedEntityGraph(name = "Book.detail", attributeNodes = @NamedAttributeNode("books"))
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @ManyToMany
    @JoinTable(
            name = "author_book",
            joinColumns = @JoinColumn(name = "author_id"),
            inverseJoinColumns = @JoinColumn(name = "book_id")
    )
    private List<Book> books;
}

and

@Entity()
@Table(name = "book")
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @ManyToMany(mappedBy = "books")
    private List<Author> authors;

}

With repositories:

 public interface AuthorRepository extends JpaRepository<Author, Long>{
        @EntityGraph(value = "Book.detail", type = EntityGraphType.LOAD)
        Author getGraphById(Long id);

        Author getById(Long id);
    }

and

public interface BookRepository extends JpaRepository<Book, Long>{

}

In AuthorRepository, i have 2 methods: getGraphById() to load books with author, getById() to not load books.

The problem is when using @test tag (jUnit test) everything works as expected, but when i call api via postman both methods load books and it is infinite like ( books -> authors-> books -> authors-> ... ).

jake101
  • 21
  • 2
  • The bi-directional relationship is causing infinite json objects. Look up `@JsonBackReference` and ` @JsonManagedReference` online to know more and fix – gtiwari333 Feb 17 '21 at 03:41

0 Answers0