title: JPA Criteria API: LEFT JOIN for optional relationships
body: <p>I'm using the Criteria API basically the first time. It's about abstracting queries for a generic builder:</p>
  
  <pre><code>public TypedQuery&lt;T&gt; newQuery( Manager&lt;?,T&gt; manager )
  {
      CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
  
      Class&lt;T&gt; genericClass = ( Class&lt;T&gt; ) ( ( ParameterizedType ) manager.getClass().getGenericSuperclass() ).getActualTypeArguments()[1];
  
      CriteriaQuery&lt;T&gt; criteriaQuery = builder.createQuery( genericClass );
      Root&lt;T&gt; root = criteriaQuery.from( genericClass );
  
      ...
  }
  </code></pre>
  
  <p>The call <code>criteriaQuery.from( genericClass );</code> generates SQL <code>INNER JOIN</code> for all relationships found on the entity by default. This is a problem, because every relationship being null (DB <code>NULL</code> or a DB that doesn't use foreign keys and has an invalid reference) those entities will be missing in the result list, effectively producing wrong search results.</p>
  
  <p>An example can be found here: <a href="https://stackoverflow.com/q/10145074/396732">JPA Criteria query Path.get left join is it possibile</a></p>
  
  <p>What I'd like to happen for queries instantiated by this class/method is that all relationships on the entity, here <code>genericClass</code>, that are mapped as <code>optional = true</code></p>
  
  <pre><code>@ManyToOne( FetchType.EAGER, optional = true )
  @JoinColumn( name = "CLOSE_USER_ID", referencedColumnName = "USER_ID" )
  private User              closer;
  </code></pre>
  
  <p>to generate an SQL <code>LEFT (OUTER) JOIN</code> instead of <code>INNER JOIN</code>.</p>
  
  <p><strong>Question</strong>:</p>
  
  <p><em>Is there standard JPQ way to get this done? If so, how?</em></p>
  
  <p>PS: there's generally no way to know the concrete type beforehand, so the only way I might be able to achieve what I need is to use the metamodel of some sort and generate the joins manually (which I'd like to avoid).</p>
  
  <hr>
  
  <p>We are using EclipseLink 2.3</p>