Search code examples
javahibernatecriteriacriteria-api

CriteriaBuilder with criteria on the child associations . Hibernate


I have orders (id, name) with oneToMany to items (id, name):

How can I fetch only these orders which have items of name 'banana' with a CriteriaBuilder:

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

    }

I get the error:

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

Solution

  • You need to use a Join. Something around these lines:

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

    alternativly you can do something like:

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