0

Given the following classes:

@Entity
public class Recipe {

    @Id
    @Column
    private long id; 

    @ElementCollection
    @CollectionTable(name = "recipe_ingredient", joinColumns = @JoinColumn(name = "id"))
    private Set<String> ingredients;

    ...
}

How can I write the in JPA using the CriteriaQuery API the following: "Given a list of ingredients, return the Recipes that have at least all of the specified ingredients"

  • Sure you want the Criteria API? It's deprecated: http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#criteria – riddle_me_this Jan 31 '17 at 04:06
  • 1
    corrected, looking for `javax.persistence.criteria.CriteriaQuery` – monkey-wrench Jan 31 '17 at 04:26
  • You can do a query with multiple "IN" clauses, one for each of the ingredients you want to check. That is true regardless of whether it is JPQL or Criteria. – Neil Stockton Jan 31 '17 at 15:43

1 Answers1

0

Offhand, it can be something like:

criteria.add(Restrictions.in("recipe.ingredients", ingredients));

where ingredients is a collection of ingredient strings. Add an alias if ingredients throws you an exception.

Warning: Criteria API is now deprecated.

Otherwise, you can take a look here for an example.

Community
  • 1
  • 1
riddle_me_this
  • 8,575
  • 10
  • 55
  • 80
  • `in` doesn't provide the result I'm looking for. This would result in a recipe just because there was one ingredient match. I only want recipes if all I've got all the ingredients. – monkey-wrench Jan 31 '17 at 04:29
  • Something like this? http://stackoverflow.com/questions/27781010/hibernate-criteria-query-collections-contains-certain-elements – riddle_me_this Jan 31 '17 at 05:13
  • same general question - doesn't look like there's much of an answer there. – monkey-wrench Jan 31 '17 at 05:26
  • Perhaps the poster mean the JPA CriteriaQuery API ... since he mentioned JPA explicitly in the question. This most certainly is not deprecated (not that it is particularly nice either). – Neil Stockton Jan 31 '17 at 11:04
  • Yes, looking for JPA CriteriaQuery API. – monkey-wrench Jan 31 '17 at 13:18