Hi and happy new year!
Considering the following (and truncated for readability sake) test case :
Code:
@Entity
@Getter
@Setter
public static class A {
@Id
@GeneratedValue(strategy = AUTO)
private long id;
@OneToOne
private B b;
}
@Entity
@Getter
@Setter
public static class B{
@Id
@GeneratedValue(strategy = AUTO)
private long id;
@OneToOne(mappedBy = "b")
private A a;
}
/**
* Fails because OneToOne's default fetch type is eager, so even if it loads with an outer join
* the B relationship, il implies 2 queries because inverse OneToOne in b is eager as well.
* Removing the inverse OneToOne leads to only one SQL.
* @throws Exception
*/
@Test
public void should_perform_only_one_select_in_owner() throws Exception {
em.getTransaction().begin();
final A a = new A();
final B b = new B();
a.setB(b);
em.persist(b);
em.persist(a);
em.getTransaction().commit();
em.clear();
final SqlCounter counter = new SqlCounter();
ds.addListener(counter);
final A a1 = em.find(A.class, a.getId());
assertThat(a1.getId()).isEqualTo(a.getId());
assertThat(counter.getCount()).isEqualTo(1); //in fact there's 2 SQL!
}
The find produces 2 SQLs and I expected only one:
Code:
Hibernate: select eagero2ote0_.id as id1_0_1_, eagero2ote0_.b_id as b_id2_0_1_, eagero2ote1_.id as id1_1_0_ from EagerO2OTest$A eagero2ote0_ left outer join EagerO2OTest$B eagero2ote1_ on eagero2ote0_.b_id=eagero2ote1_.id where eagero2ote0_.id=?
Hibernate: select eagero2ote0_.id as id1_0_1_, eagero2ote0_.b_id as b_id2_0_1_, eagero2ote1_.id as id1_1_0_ from EagerO2OTest$A eagero2ote0_ left outer join EagerO2OTest$B eagero2ote1_ on eagero2ote0_.b_id=eagero2ote1_.id where eagero2ote0_.b_id=?
It seems while loading A, B is eagerly loaded (fine, that complies the spec), but while loading B, A and B are loaded once again and I'm surprised because both instances should be included in the persistence context.
Wouldn't be possible to use the A and B instances currently loaded and thus avoiding an unneeded SQL or may be the loading process is not completed and they're not yet included in the persistence context?
Regards