9

I have created two entities Book and Book_Category with one-to-many relationship. When I issued BookCategoryRepository.findAll(), I expected hibernate to use 'INNER JOIN' query. But it just issued query to take data from Book_Category.

What I am missing? What should I do to make hibernate issue JOIN query?

Book.java

@Entity
public  class Book {

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

    @ManyToOne
    @JoinColumn(name = "book_category_id")
    private BookCategory bookCategory;
}

BookCategory.java

@Entity
@Table(name = "book_category")
public  class BookCategory {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    @OneToMany(mappedBy = "bookCategory", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<Book> books;
}

BookCategoryRepository.java

public  interface BookCategoryRepository extends JpaRepository<BookCategory, Integer> {
}


bookCategoryRepository.findAll()
M. Deinum
  • 115,695
  • 22
  • 220
  • 224
Manoj
  • 5,707
  • 19
  • 56
  • 86
  • The join happens since you have that on the entity. the entity BookCategory also has a set of Books so when you do findAll() you should be receiving a set of books as well. What is it that you are trying to achieve here. You can write a @query if you really need to see JOIN in the query. – Grinish Nepal Apr 07 '16 at 23:54
  • Hibernate is issuing only select * from Book_category. I expect it to issue select * from book_Category inner join Book b. I have already set FetchType to eager. So I don't want to use @Query. – Manoj Apr 08 '16 at 00:28
  • @GrinishNepal `@query` is also not working on that case. – NaN Nov 06 '17 at 15:12

1 Answers1

15

Hibernate uses by default a second query to retriev the child collection. One reason for this is a proper limit query. Otherwise, there would be more rows in the result set, than entities for the 1 side, if at least one has more than 1 child.

There exists an annotation to change this behaviour in hibernate which is ignored by the Spring Data Jpa Repositories. The annotation is @Fetch(FetchMode.JOIN). You might consider How does the FetchMode work in Spring Data JPA if you really need this behaviour.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
mh-dev
  • 5,264
  • 4
  • 25
  • 23