本文介绍了为什么spring data jpa不发出JOIN查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个具有一对多关系的实体 BookBook_Category.当我发布 BookCategoryRepository.findAll() 时,我希望 hibernate 使用INNER JOIN"查询.但它只是发出查询以从 Book_Category 中获取数据.

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.

我错过了什么?我应该怎么做才能使 hibernate 问题 JOIN 查询?

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

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

BookCategoryRepository.java

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


bookCategoryRepository.findAll()

推荐答案

Hibernate 默认使用第二个查询来检索子集合.原因之一是适当的限制查询.否则,结果集中的行将多于 1 侧的实体,如果至少有一个有 1 个以上的子项.

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.

存在一个注释来更改休眠中的此行为,Spring Data Jpa 存储库会忽略该注释.注释是@Fetch(FetchMode.JOIN).您可能会考虑 FetchMode 在 Spring Data JPA 中是如何工作的 如果你真的需要这种行为.

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.

这篇关于为什么spring data jpa不发出JOIN查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 08:30