we have a n+1 select problem with Hibernate 3.3.

For simplicity's sake, I'll just do a short abstract example.

Suppose we have the following simple classes:

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")
}

So as you can see SubEntity has a relation to MainEntity that is expressed by two properties, where the mainId property is the one responsible for managing the relation/foreign key.

This works quite well and perfectly fits our needs.

However, there's one problem with eagerly loading the SubEntity along with the MainEntity.

Suppose I have a query that returns a collection of MainEntity. With the current setup, Hibernate will issue n + 1 selects: the query itself + n selects for each SubEntity.

Of course I could add a join fetch to the query, but I'd rather like Hibernate to do that automatically. Thus I tried adding @Fetch( FetchMode.JOIN ), but that didn't do anything.

I would also have no problem using @Fetch( FetchMode.SUBSELECT ), 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 @CollectionOfElements and @Fetch( FetchMode.SUBSELECT )).


So the question is: how woul

Edit
Report