title: How to properly apply join fetch in JPA Criteria API
body: <p>I am using JPA Criteria API in a Spring data JPA based application. My service class uses static methods to retrieve <code>Specifications</code> which can then be combined together to form a particular query. E.g.</p>
  
  <pre><code>repository.findAll(where(matchById(str)).or(matchByName(str)))
  </code></pre>
  
  <p>Here, I am using two methods that return Specifications with the appropriate criteria applied to it. This is how the two methods look like</p>
  
  <pre><code>public static Specification&lt;SomeEntity&gt; matchById(String str) {
      return (root, criteriaQuery, cb) -&gt; 
          cb.like(root.get(SomeEntity_.id).as(String.class), str + "%");
  }
  
  public static Specification&lt;SomeEntity&gt; matchByName(String str) {
      return (root, criteriaQuery, cb) -&gt; {
          cb.or(cb.like(cb.lower(root.get(SomeEntity_.firstName)), str.toLowerCase() + "%"),
                cb.like(cb.lower(root.get(SomeEntity_.lastName)), str.toLowerCase() + "%")
          );
  }
  </code></pre>
  
  <p>This works fine. I want to add a </p>
  
  <p><code>root.fetch(SomeEntity_.employee, JoinType.INNER);</code></p>
  
  <p>in such a way that all queries that are built using any combination of static Specifications methods, utilize the <code>FETCH JOIN</code>.</p>
  
  <p>If I add this statement to both static methods, then the INNER JOIN is applied twice which doesnt seem right. Ideally, I think I should have another static method that only applies the <code>FETCH JOIN</code> and return the Specifications but I cant seem to figure out how to return a <code>Predicate</code> without using any of the <code>criteriaBuilder</code> methods. To clarify, this is how my method should look like:</p>
  
  <pre><code>public static Specification&lt;SomeEntity&gt; start() {
      return (root, criteriaQuery, criteriaBuilder) -&gt; {
          root.fetch(SomeEntity_.employee, JoinType.INNER);
  
          // NOW RETURN WHAT ???
          return null;
      };
  }
  </code></pre>
  
  <p>Any help would be appreciated. </p>