title: Spring Data JPARepository: How to conditionally fetch children entites
body: <p>How can one configure their JPA Entities to not fetch related entities unless a certain execution parameter is provided. </p>
  
  <p>According to Spring's documentation, <a href="http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.entity-graph" rel="noreferrer">4.3.9. Configuring Fetch- and LoadGraphs</a>, you need to use the <code>@EntityGraph</code> annotation to specify fetch policy for queries, however this doesn't let me decide at runtime whether I want to load those entities.</p>
  
  <p>I'm okay with getting the child entities in a separate query, but in order to do that I would need to configure my repository or entities to not retrieve any children. Unfortunately, I cannot seem to find any strategies on how to do this. <code>FetchPolicy</code> is ignored, and <code>EntityGraph</code> is only helpful when specifying which entities I want to eagerly retrieve. </p>
  
  <p>For example, assume <code>Account</code> is the parent and <code>Contact</code> is the child, and an Account can have many Contacts. </p>
  
  <p><strong>I want to be able to do this:</strong> </p>
  
  
  
  <pre><code>if(fetchPolicy.contains("contacts")){
    account.setContacts(contactRepository.findByAccountId(account.getAccountId());
  }
  </code></pre>
  
  <p>The problem is spring-data eagerly fetches the contacts anyways.</p>
  
  <p><strong>The Account Entity class looks like this:</strong> </p>
  
  
  
  <pre><code>@Entity
  @Table(name = "accounts")
  public class Account
  {
      protected String accountId;
      protected Collection&lt;Contact&gt; contacts;
  
      @OneToMany
      //@OneToMany(fetch=FetchType.LAZY) --&gt; doesn't work, Spring Repositories ignore this
      @JoinColumn(name="account_id", referencedColumnName="account_id")
      public Collection&lt;Contact&gt; getContacts()
      {
          return contacts;
      }
  
      //getters &amp; setters
  
  }
  </code></pre>
  
  <p><strong>The AccountRepository class looks like this:</strong></p>
  
  
  
  <pre><code>public interface AccountRepository extends JpaRepository&lt;Account, String&gt;
  {
      //@EntityGraph ... &lt;-- has type= LOAD or FETCH, but neither can help me prevent retrieval
      Account findOne(String id);
  }
  </code></pre>