带有子关联标准的 CriteriaBuilder。休眠

CriteriaBuilder with criteria on the child associations . Hibernate

我有订单 (id, name) 与 oneToMany 到项目 (id, name):

如何使用 CriteriaBuilder 仅获取名称为 'banana' 的订单:

   @Override
    public Order orderQuery() {

        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery criteriaQuery = cb.createQuery(Order.class);
        Root root = criteriaQuery.from(Order.class);
        root.fetch("items", JoinType.INNER);
        CriteriaQuery d = criteriaQuery.select(root);

        criteriaQuery.where(cb.equal(root.get("item.name"), "banana"));
        return (Order)this.entityManager.createQuery(criteriaQuery).getSingleResult());

    }

我收到错误:

Unable to locate Attribute  with the the given name [item.name] on

您需要使用连接。这些行周围的东西:

Join< Order ,Item> joinItems = root.join("items");
criteriaQuery.where(cb.equal(joinItems.get("item.name"), "banana"));

或者你可以这样做:

criteriaQuery.where(cb.equal(root.get("items").get("name"), "banana"));