我有实体:
class Parent {
...
@OneToMany(Fetch = FetchType.EAGER)
@OrderBy("id")
private List<Child> children;
}
class Child{
...
@OneToMany(Fetch = FetchType.LAZY)
@OrderBy("id")
private List<GrandChild> grandChildren;
}
class GrandChild {
...
}
我想查询分页的孩子,也要获取大孩子。我也按名称过滤儿童,但我认为这并不重要。我有这样的JPQL查询:
@Query("select c " +
"from Parent p " +
"inner join p.children c " +
"inner join fetch c.grandchildren g " +
"where p = :parent and " +
"c.childName like concat(:childName,'%')")
Page<Expense> findBy(@Param("parent") Parent parent, @Param("childName")String childName, Pageable pageable);
在启动spring boot应用程序期间,引发了异常:
查询指定了连接提取,但选择列表中不存在所提取关联的所有者
消息很简单,但是我不能添加父项来选择语句,因为我只希望孩子。
答案 0 :(得分:1)
c.grandchildren缺少别名e
@Query("select e " +
"from Parent p " +
"inner join p.children c " +
"inner join fetch c.grandchildren e" +
"where p = :parent and " +
"c.childName like concat(:childName,'%')")
Page<Expense> findBy(@Param("parent") Parent parent, @Param("childName")String childName, Pageable pageable);
答案 1 :(得分:0)
我发现,当您想要获取数据页面时,您不能使用join fetch
,因此请按照此question。我在JpaRepository中创建了两个方法。
之后的代码如下:
@Query("select c.id " +
"from Parent p " +
"inner join p.children c " +
"where p = :parent and " +
"c.childrenName like concat(:childrenName,'%')")
Page<Long> findIdsBy(@Param("parent") Parent parent,
@Param("childrenName") String childrenName,
Pageable pageable);
@Query("from Children c join fetch c.grandChildren where c.id in :ids")
List<Children> getChildrenByIdWithGrandChildren(@Param("ids") List<Long> ids);