为什么spring data jpa不发布JOIN查询? [英] Why spring data jpa not issuing JOIN query?

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

问题描述

我用一对多关系创建了两个实体 Book Book_Category 。当我发行 BookCategoryRepository.findAll()时,我期望hibernate使用'INNER JOIN'查询。但它只是发出查询来从Book_Category中获取数据。



我缺少什么?我应该怎么做才能让hibernate发出JOIN查询?



Book.java

 公共类书籍{

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
私人字符串名称;

@ManyToOne
@JoinColumn(name =book_category_id)
私人BookCategory bookCategory;
}

BookCategory.java

< pre $ @Entity
@Table(name =book_category)
public class BookCategory {

@Id
@GeneratedValue (strategy = GenerationType.AUTO)
private int id;
私人字符串名称;
@OneToMany(mappedBy =bookCategory,fetch = FetchType.EAGER,cascade = CascadeType.ALL)
private Set< Book>图书;

BookCategoryRepository.java

  public interface BookCategoryRepository扩展JpaRepository< BookCategory,Integer> {
}


bookCategoryRepository.findAll()


解决方案

Hibernate默认使用第二个查询来检索子集合。其中一个原因是适当的限制查询。否则,结果集中的行数将比1方的实体数多,如果至少有一个孩子超过1个。

存在一个注释来改变hibernate中的这种行为,Spring Data Jpa Repositories忽略了这种行为。注释是 @Fetch(FetchMode.JOIN)。您可能会考虑 FetchMode如何在Spring Data JPA中工作< a>如果你真的需要这种行为。


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()

解决方案

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆