I want to create a simple many-to-many relation by using spring jpa and hibernate, here's the code:
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "name")
private String name;
@ManyToMany(cascade = CascadeType.ALL,
fetch = FetchType.LAZY)
@JoinTable(name = "book_publisher",
joinColumns = @JoinColumn(name = "book_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "publisher_id", referencedColumnName = "id"))
private Set<Publisher> publishers;
and
@Entity
public class Publisher {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@ManyToMany(mappedBy = "publishers"
, fetch = FetchType.LAZY)
@Nullable
private Set<Book> books = new HashSet<>();
public Publisher(String name) {
this.name = name;
}
The collections are all lazily fetched as the code shown above.
And I create two repositories of there two entities:
public interface PublisherRepository extends JpaRepository<Publisher, Integer>{
}
public interface BookRepository extends JpaRepository<Book, Integer>{
}
And I create a simple controller:
@GetMapping("/getPublisher/{id}")
public Publisher getPublisher(@PathVariable Integer id) {
return publisherRepository.findById(id).get();
}
something strange happens:
when I make a http call via curl, I received such response:
{"id":1,"name":"YanYan","books":[{"id":1,"name":"Avengers","publishers":[{"id":1,"name":"YanYan","books":[{"id":1,"name":"Avengers","publishers":[{"id":1,"name":"YanYan","books":[{"id":1,"name":"Avengers","publishers":[{"id":1,"name":"YanYan","books":[{"id":1,"name":"Avengers","publishers":[{"id":1,"name":"YanYan","books":[{"id":1,"name":"Avengers","publishers":[{"id" .....
which indicates none of them are lazily fetched, this causes a infinite loop.
Can anyone tell me why?