@Fetch(FetchMode.JOIN)与JpaRepository findOne()一起使用,但不与findAll()

时间:2017-12-03 21:30:18

标签: java hibernate spring-boot spring-data-jpa

我有一个@ManyToOne关系

的班级
@Table(name = "answers")
public class Answer implements Serializable {

  @Id
  @GeneratedValue(strategy= GenerationType.IDENTITY)
  @Column(name = "answer_id")
  private Long answerId;    

  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "category_id",referencedColumnName = "category_id")
  @Fetch(FetchMode.JOIN)
  private Category category;
}

简单的存储库

@Repository
public interface AnswerRepository extends JpaRepository<Answer, Long> {
}

在我的答案控制器中,我有两个方法,一个使用AnswerRepository.findOne()返回单个答案,使用AnswerRepository.findAll()返回所有答案的第二个返回列表

问题是@Fetch完全适用于findOne(),(使用JOIN和SELECT检查,将查询从连接更改为两个单独的查询), 但由于.findAll()它不起作用,我总是会收到一个主要查询+ n个额外查询所需的每个类别。

我希望findAll()也受到@Fetch的影响或其他一些不能获得n个查询的方式,因为目前它很慢并且需要大量查询来获取答案列表,但是我无法找到任何方法让它发挥作用。

我真的很感激任何答案。谢谢你的帮助。

(缩写为id字段查询) 找到一个查询:

select 
  answer0_.answer_id as answer_i1_0_0_,
  .
  category1_.category_id as category1_1_1_,
  .
from answers answer0_ 
inner join categories category1_ on 
  answer0_.category_id=category1_.category_id 
where answer0_.answer_id=?

findAll查询:

select answer0_.answer_id as answer_i1_0_,
   answer0_.category_id as category6_0_
from answers answer0_

select category0_.category_id as category1_1_0_
from categories category0_ 
where category0_.category_id=?

select category0_.category_id as category1_1_0_
from categories category0_ 
where category0_.category_id=?

select category0_.category_id as category1_1_0_
from categories category0_
where category0_.category_id=?

select category0_.category_id as category1_1_0_
from categories category0_
where category0_.category_id=?

select category0_.category_id as category1_1_0_
from categories category0_
where category0_.category_id=?

select category0_.category_id as category1_1_0_
from categories category0_
where category0_.category_id=?

0 个答案:

没有答案