我正在尝试使用CriteriaBuilder过滤相关的Child-Entities但是没有得到它。我拥有的实体是:
@Entity
public class Parent {
@ManyToOne
private Car car;
@OneToMany
private List<Child> children;
}
@Entity
public class Child {
private Long value;
}
@Entity
public class Car {
private Long id;
}
我想根据值过滤孩子,即我不想得到所有孩子,但那些值在值列表中。
我试过这样:
@Override
public List<Parent> loadParents(final long carId, final List<ParentType> types, final List<Long> values) {
final CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
final CriteriaQuery<Parent> select = criteriaBuilder.createQuery(Parent.class);
final Root<Parent> from = select.from(Parent.class);
final List<Predicate> predicates = new ArrayList<>();
predicates.add(criteriaBuilder.equal(from.get("car").get("id"), carId));
if (!CollectionUtils.isEmpty(types)) {
predicates.add(from.get("type").in(types));
}
if (!CollectionUtils.isEmpty(values)) {
final ListJoin<Parent, Child> join = from.join(em.getMetamodel().entity(Parent.class).getList("children", Child.class));
final Predicate predicate = join.get(em.getMetamodel().entity(Child.class).getDeclaredSingularAttribute("value", Long.class)).in(values);
predicates.add(predicate);
}
select.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
final List<Parent> result = em.createQuery(select).getResultList();
return result;
}
但我没有得到我想要的结果。删除
if (!CollectionUtils.isEmpty(values)) {
final ListJoin<Parent, Child> join = from.join(em.getMetamodel().entity(Parent.class).getList("children", Child.class));
final Predicate predicate = join.get(em.getMetamodel().entity(Child.class).getDeclaredSingularAttribute("value", Long.class)).in(values);
predicates.add(predicate);
}
我让父母和他们相应的孩子在一起。任何人都可以暗示我做错了吗?
由于