title: Hibernate OneToOne automatic join fetching (resolving n+1 problem)
body: <p>we have a n+1 select problem with Hibernate 3.3.</p>
  
  <p>For simplicity's sake, I'll just do a short abstract example.</p>
  
  <p>Suppose we have the following simple classes:</p>
  
  <pre><code>class MainEntity {
    @Id
    public Long id; //we have a table generator create this id
  
    @OneToOne ( mappedBy ="main" )
    public SubEntity subEntity;
  }
  
  class SubEntity {
   @Id
   @Column( name = "mainId" ) //note that this is the same column as the join column below
   public Long mainId; //in order to have the exact same id as the corresponding MainEntity
  
   @OneToOne ( fetch = FetchType.LAZY )
   @JoinColumn ( name = "mainId", insertable = false, updatable = false, nullable = false )
   public MainEntity main; //this is used for navigation and queries (" ... subentity.main = :x")
  }
  </code></pre>
  
  <p>So as you can see <code>SubEntity</code> has a relation to <code>MainEntity</code> that is expressed by two properties, where the <code>mainId</code> property is the one responsible for managing the relation/foreign key.</p>
  
  <p>This works quite well and perfectly fits our needs.</p>
  
  <p>However, there's one problem with eagerly loading the <code>SubEntity</code> along with the <code>MainEntity</code>.</p>
  
  <p>Suppose I have a query that returns a collection of <code>MainEntity</code>. With the current setup, Hibernate will issue n + 1 selects: the query itself + n selects for each <code>SubEntity</code>.</p>
  
  <p>Of course I could add a <code>join fetch</code> to the query, but I'd rather like Hibernate to do that automatically. Thus I tried adding <code>@Fetch( FetchMode.JOIN )</code>, but that didn't do anything.</p>
  
  <p>I would also have no problem using <code>@Fetch( FetchMode.SUBSELECT )</code>, which should reduce the select statements to 2 - the original query and a select for the sub entities (at least that's what happens on another property annotated with <code>@CollectionOfElements</code> and <code>@Fetch( FetchMode.SUBSELECT )</code>).
  <br>
  <br>
  <br>
  So the question is: how would I tell Hibernate to <i>automatically</i> join fetch or use a single select in order to eagerly load the sub entities? Am I missing something?
  <br>
  <br>
  Thanks in advance,</p>
  
  <p>Thomas</p>
  
  <p>PS: One thing that might be a problem might be the <code>mappedBy = "main"</code> which doesn't reference the actual id column, but I can't change it to <code>mappedBy = "id"</code>.</p>