title: JPA criteria query in a many-to-many relationship using IN operator
body: <p>I have the following two entities:</p>
  
  <p><strong>Profile, Category</strong></p>
  
  <p>In the Profile entity i have a List of categories that the profile has</p>
  
  <p>In the Category entity i have a List of profiles that the category has</p>
  
  <p>The generated table is called <strong>profiles_has_categories</strong> and has the following columns:</p>
  
  <p><strong>profile_id, category_id</strong> </p>
  
  <p>I want to find all profiles that belong to any of the categories with the following ids 1, 2, 3, 4</p>
  
  <p>I would do that in plain sql with:</p>
  
  <pre><code>SELECT p.* FROM profiles p, profiles_has_categories phc 
  WHERE p.id = phc.profile_id 
  AND phc.category_id IN (1, 2, 3, 4)
  </code></pre>
  
  <p>But i can't figure out how to do that using the CriteriaBuilder to construct a query in JPA:</p>
  
  <pre><code>CriteriaBuilder cb = em.getCriteriaBuilder();
  CriteriaQuery&lt;Profile&gt; criteria = cb.createQuery(Profile.class);
  Root&lt;Profile&gt; root = criteria.from(Profile.class);
  
  // Profile_.categories is a collection of Category objects
  // categories is collection of Long (category ids) that i want to search in
  // but is not working
  criteria.where(root.get(Profile_.categories).in(categories))
  
  List&lt;Profile&gt; results = em.createQuery(criteria).getResultList();
  </code></pre>