簡體   English   中英

帶有注釋的JPA本機查詢執行不同的查詢

[英]JPA native query with annotation executes different query

我正在嘗試實現這樣的示例: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:我已經在“ findOne”方法的本機輸出上編寫了查詢。 最后添加“和收藏夾me1_.favorite_place_order = 0”。 我也嘗試使用不帶任何修改的確切查詢,它像一個魅力一樣工作!!

第二個查詢用於加載用FetchType.EAGER定義的favouritePlaces

您的存儲庫正在查詢人,但不是場所,並且由於FetchType。EAGER還會在第二個查詢中加載所有場所; 要查詢地方,請使用PlacesRepository。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM