Note that there are some explanatory texts on larger screens.

plurals
  1. POAvoiding n+1 eager fetching of child collection element association
    primarykey
    data
    text
    <p>I have the following classes:</p> <pre><code>@Entity @Table(name = "base") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "DISCRIMINATOR", discriminatorType = DiscriminatorType.STRING) @ForceDiscriminator public class Base { // ... } @Entity @DiscriminatorValue("foo") public class Foo extends Base { @OneToMany( mappedBy = "foo", cascade=CascadeType.ALL ) private List&lt;Bar&gt; bars = new ArrayList&lt;Bar&gt;(); // ... } @Entity public class Bar { @ManyToOne (optional = false) @JoinColumn(name = "foo_id" ) private Foo foo; @OneToOne @JoinColumn(name = "baz_id", nullable = false) private Baz baz; //... } @Entity public class Baz { // ... } </code></pre> <p>Now I basically want to load all <code>Base</code>, but eager load bars when applicable, so I use the following query:</p> <pre><code>SELECT b FROM Base b LEFT JOIN FETCH b.bars </code></pre> <p>While this works, it seems to generate a SELECT N+1 problem for the Bar entities:</p> <pre><code>Hibernate: /* SELECT b FROM Base b LEFT JOIN FETCH b.bars */ SELECT ... Hibernate: /* load com.company.domain.Baz */ SELECT ... Hibernate: /* load com.company.domain.Baz */ SELECT ... </code></pre> <p>Is it possible to tell hibernate to eagerly load an association for each element in the child collection without resorting to N+1 SELECTs?</p> <p>I tried something along the lines of the following query, which obviously does not work since its a collection:</p> <pre><code>SELECT b FROM Base b LEFT JOIN FETCH b.bars LEFT JOIN FETCH b.bars.baz //Results in: illegal attempt to dereference collection [Foo.id.bars] with element property reference [baz] </code></pre> <p>I also tried using <code>IN(b.bars) bars</code>, and while this allows me to reference the child collection, it does not seem to eagerly load the bars collection which is my goal.</p> <p>An explanation of why this happens would also be nice, since I cannot seem to figure it out.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload