Spring Data Jpa 關於fetch join 的錯誤
spring data jpa 文件的官方網站:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/
在開發中使用到 Jpa Dao 方法時,出現如下錯誤:
fetch join...
but the owner of the fetched association was not present in the select list。。。
原因是和使用了 left join fetch 關鍵字有關,可以理解為使用 join 查詢的表,並沒有出現在 select 關鍵字之後。
就是說查詢的結果集中沒有直接關聯到join表的屬性。
我的真實情況如下:
寫成如下,正常編譯
@Query("SELECT o FROM Order o left join fetch o.orderStatus where o.creation between ?1 and ?2 and o.removed=?3")
List<Order> findByCreationBetweenAndRemoved(Date beginDate, Date endDate, boolean b);
改為如下,則出現上述所說的錯誤
@Query("SELECT o.id FROM Order o left join fetch o.orderStatus where o.creation between ?1 and ?2 and o.removed=?3")
原因就是 left join fetch 後面的o.orderStatus 對應的實體表,並沒有在o.id中出現。
修改比較簡單,
1,返回值用包含join表的實體接受
2,去掉left join fetch關聯