【问题标题】:How to filter parent object which has list of children and a child has list of grand children and by matching property of grand children如何过滤具有子列表的父对象和具有孙子列表的子对象并通过匹配孙子的属性
【发布时间】:2020-07-17 03:14:24
【问题描述】:

对象层次如下。

CoverCategory 有多个 Cover,一个 Cover 有多个 SubCover。 让我们在编码中这样说

封面类别

@Entity
public class CoverCategory {

@Id
private Long id;

@OneToMany
List<Cover> coverList;

}

封面

@Entity
public class Cover {

 @Id
 private Long id;

 @ManyToOne
 private CoverCategory coverCategory;

 @OneToMany
 private List<SubCover> subCoverList;

}

副封面

@Entity
public class SubCover {

       @Id
       private Long id;

       @ManyToOne
       private Cover cover;

       private String name;
}

我在这里尝试做的是选择所有具有子封面名称“subcover1”的封面类别

我尝试编写如下代码

String name = "subcover1";
Session session = getCurrentSession();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<CoverCategory> creteriaQuery = criteriaBuilder.createQuery(CoverCategory.class);
Root<CoverCategory> root = creteriaQuery.from(CoverCategory.class);
creteriaQuery.select(root).where(criteriaBuilder.equal(root.get("coverList").get("subCoverList").get("name"),name));
Query<CoverCategory> query = session.createQuery(creteriaQuery);
List<CoverCategory> results = query.getResultList();

但它给了我以下异常

org.springframework.dao.InvalidDataAccessApiUsageException: Illegal attempt to dereference path source [null.coverList] of basic type; nested exception is java.lang.IllegalStateException: Illegal attempt to dereference path source [null.coverList] of basic type  

谁能告诉我如何正确地做到这一点。提前致谢。 只需要在标准生成器中完成

【问题讨论】:

  • 尝试在root.get("coverList")之前做一个root.join("coverList")"subCoverList"也是如此
  • 如果您不反对使用 JPQL 而不是 Criteria Queries,您可以查看 this other example。我相信您的等效查询是SELECT cc FROM CoverCategory cc LEFT JOIN Cover c LEFT JOIN SubCover sc WHERE sc.name = :param
  • 我相信他特别说过“只需要在标准生成器中完成”

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


【解决方案1】:
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<CoverCategory> criteriaQuery = criteriaBuilder.createQuery(CoverCategory.class);
Root<CoverCategory> root = criteriaQuery.from(CoverCategory.class);
Join<CoverCategory,Cover> coverJoin = root.join("coverList");
Join<Cover, SubCover> subjoin = coverJoin.join("subCoverList");
criteriaBuilder.equal(subjoin.get("name"),name);
Query<CoverCategory> query = session.createQuery(criteriaQuery);
List<CoverCategory> results = query.getResultList();

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 2011-09-29
  • 2022-01-23
  • 1970-01-01
  • 2013-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多