title: Hibernate JPA QueryBuilder.like
body: <p>I recently trying to refactor my Hibernate Session API to JPA API and I ran in to some problems</p>
  
  <p>Here is my old Session code</p>
  
  <pre><code>Criteria criteria = session().createCriteria(Book.class);       
  
      // SEARCH both name, ispn field in the db
      if( search != null &amp;&amp; !search.isEmpty() ){
          Criterion name = Restrictions.ilike("name", search, MatchMode.ANYWHERE);  // This use to return a list of similar results..
          Criterion ispn = Restrictions.ilike("ispn", search, MatchMode.ANYWHERE);
  
          LogicalExpression orExp = Restrictions.or(name, ispn);
  
          criteria.add(orExp);
      }
  </code></pre>
  
  <p>Here is my try of implementing CriteriaBuilder</p>
  
  <pre><code>CriteriaBuilder builder = entityManager.getCriteriaBuilder();
  
      CriteriaQuery&lt;Book&gt; criteria = builder.createQuery(Book.class);
  
      Root&lt;Book&gt; root = criteria.from(Book.class);
  
      criteria.select(root);
  
  
  
      if( search != null &amp;&amp; !search.isEmpty() ){
  
          System.out.println(search);
  
          Predicate predicateName = builder.like(root.get(Book_.name), search); // root.get(Book_.name) must match exactly `search` for it to return anything.
  
          // Predicate predicateIspn = builder.like(root.get(Book_.ispn), search);
  
          criteria.where(predicateName);
      }
  
      List&lt;Book&gt; books = entityManager.createQuery(criteria).getResultList();
  
      return books;
  </code></pre>
  
  <p><strong>Questions</strong></p>
  
  <ol>
  <li><code>Predicate predicateName = builder.like(root.get(Book_.name), search);</code>  CirteriaBuilder.like doesn't seem to work I have to make sure <code>search</code> matches perfectly to <code>root.get(Book_.name)</code> for it to return results.</li>
  </ol>
  
  <p>I have looked at hibernate docs it seems like CriteriaBuilder.like only takes 2 argument one is taken from db mapping<code>root.get(Book_.name)</code> compare to input <code>search</code> there is no option where I can tell it to MatchMode.ANYWHERE.  Any suggestions? or maybe I use the wrong method?</p>
  
  <ol start="2">
  <li><code>LogicalExpression orExp = Restrictions.or(name, ispn);</code> it use to check if the input matches <code>name</code> or <code>ispn</code>.  But with JPA CriteriaBuilder how would I do this?  I looked around for some tutorials Just couldn't find a tutorial that has a complete CRUD examples...  </li>
  </ol>
  
  <p>Thank you,</p>