如何过滤具有子项列表的父对象和具有子项列表的子项并通过匹配子项的属性来过滤

时间:2019-04-11 09:46:57

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

对象层次结构如下。

CoverCategory具有多个Cover,一个Cover具有多个SubCovers。 让我们说一下,在编码中

CoverCategory

@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  

有人可以告诉我如何正确执行此操作。提前致谢。 只需在条件构建器中完成

1 个答案:

答案 0 :(得分:0)

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();