我正在尝试实现这样的示例:Person类有一个它喜欢的地方列表。但是当我想查询它时,我希望结果为每个人只有最喜欢的地方(只是第一个不是全部)。所以我这样做了:
@Entity
class Person{
...
@ManyToMany(cascade = {CascadeType.REFRESH,CascadeType.PERSIST}, fetch = FetchType.EAGER)
@JoinTable(name = "person_favorite_place",
joinColumns = @JoinColumn(name = "person_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "place_id", referencedColumnName = "id")
)
@OrderColumn(name="favorite_place_order")
List<Place> favoritePlaces;
}
在存储库中,我做了:
public interface PersonRepository extends JpaRepository<Person, Long> {
@Query(value = "select person0_.id as id1_0_0_, person0_.age as age2_0_0_, person0_.name as name3_0_0_, favoriteme1_.person_id as person_id1_1_1_, place2_.id as place_id2_1_1_, favoriteme1_.favorite_place_order as favorite3_1_, place2_.id as id1_3_2_, place2_.invented as invented2_3_2_, place2_.name as name3_3_2_ from person person0_ left outer join person_favorite_place favoriteme1_ on person0_.id=favoriteme1_.person_id left outer join place place2_ on favoriteme1_.place_id=place2_.id where person0_.id=:personId and favoriteme1_.favorite_place_order = 0", nativeQuery = true)
Person getPersonWithFavoritePlace(@Param("personId") Long personId);
}
但是看起来,有2个sql查询正在运行。第一个是:
select person0_.id as id1_0_0_, person0_.age as age2_0_0_, person0_.name as name3_0_0_, favoriteme1_.person_id as person_id1_1_1_, place2_.id as place_id2_1_1_, favoriteme1_.favorite_place_order as favorite3_1_, place2_.id as id1_3_2_, place2_.invented as invented2_3_2_, place2_.name as name3_3_2_ from person person0_ left outer join person_favorite_place favoriteme1_ on person0_.id=favoriteme1_.person_id left outer join place place2_ on favoriteme1_.place_id=place2_.id where person0_.id=:personId and favoriteme1_.favorite_place_order = 0
第二个:
select favoriteme0_.person_id as person_id1_1_0_, favoriteme0_.place_id as place_id2_1_0_, favoriteme0_.favorite_place_order as favorite3_0_, place1_.id as id1_3_1_, place1_.invented as invented2_3_1_, place1_.name as name3_3_1_ from person_favorite_place favoriteme0_ inner join place place1_ on favoriteme0_.place_id=place1_.id where favoriteme0_.person_id=?
我能理解第一个,这完全是我想要执行的查询,但第二个,我不知道它来自哪里。所以我认为,因为我拥有一个人最喜欢的地方但不是最想要的地方。
有什么想法吗?
BR
PS:我已经在&#34; findOne&#34;的原生输出上写了查询。方法。刚添加&#34;和favoriteme1_.favorite_place_order = 0&#34;到底。此外,我试图使用确切的查询而不进行修改,它就像一个魅力!!
答案 0 :(得分:0)
第二个查询用于加载您使用FetchType.EAGER定义的favoritePlaces
答案 1 :(得分:0)
您的存储库正在查询人员而不是地点,因为FetchType.EAGER也会使用第二个查询加载所有地方;查询Places使用PlacesRepository。