These are chat archives for hibernate/hibernate-orm

22nd
Jun 2018
Giovanni Lovato
@heruan
Jun 22 08:42

Given these entities:

@Entity
class Foo {

    @Id
    String id;

    @OneToOne
    Bar bar;

}

@Entity
class Bar {

    @Id
    String id;

    String name;

    @OneToOne(mappedBy = "bar")
    Foo foo;

}

this code

CriteriaQuery<Foo> criteriaQuery = em.getCriteriaBuilder().createQuery(Foo.class);
criteriaQuery.from(Foo.class);
em.createQuery(criteriaQuery).getResultList();

generates this three queries

select 
    foo0_."id" as id1_1_, 
    foo0_."bar_id" as bar_id2_1_ 
from 
    "Foo" foo0_ 

select 
    bar0_."id" as id1_0_0_, 
    bar0_."name" as name2_0_0_, 
    foo1_."id" as id1_1_1_, 
    foo1_."bar_id" as bar_id2_1_1_ 
from 
    "Bar" bar0_ 
    left outer join "Foo" foo1_ on bar0_."id" = foo1_."bar_id" 
where 
    bar0_."id" = ? 

select 
    foo0_."id" as id1_1_1_, 
    foo0_."bar_id" as bar_id2_1_1_, 
    bar1_."id" as id1_0_0_, 
    bar1_."name" as name2_0_0_ 
from 
    "Foo" foo0_ 
    left outer join "Bar" bar1_ on foo0_."bar_id" = bar1_."id" 
where 
    foo0_."bar_id" = ?

But wouldn't this single query be enough to get all the required fields for both entities?

select 
    foo0_."id" as id1_1_1_, 
    foo0_."bar_id" as bar_id2_1_1_, 
    bar1_."id" as id1_0_0_, 
    bar1_."name" as name2_0_0_ 
from 
    "Foo" foo0_ 
    left outer join "Bar" bar1_ on foo0_."bar_id" = bar1_."id"
Giovanni Lovato
@heruan
Jun 22 09:18
Found HHH-3930 but I'm still experiencing this in 5.3.1 :confused:
Giovanni Lovato
@heruan
Jun 22 10:11
I'm reading a lot on this and it seems the default fetch mode for eager association with the Criteria API is SELECT. One can force a JOIN fetch with root.fetch(...), but this is per-field basis. What I cannot understand is why this is the default for *ToOne association: isn't a JOIN fetch always better than SELECT for *ToOnes?