0

I ave observed the following in the case on JPA-HIbernate one to one association :

When one to one association using Lazy fetch - It fires SELECT queries

class A {
    @OneToOne(fetch = FetchType.LAZY, mappedBy = "a", cascade = { CascadeType.PERSIST, CascadeType.MERGE })
    public B getB() {
        return B;
    }
}

When one to one association using EAGER fetch - It fires JOIN queries

class A {
    @OneToOne(fetch = FetchType.EAGER, mappedBy = "a", cascade = { CascadeType.PERSIST, CascadeType.MERGE })
    public B getB() {
        return B;
    }
}

What I have observed is in case 1, also there is nothing lazy but the SELECT queries are fired almost immediately when the parent entity is loaded.

Does lazy load really work in case default configurations in JPA-Hibernate or it is always EAGER with SELECT/JOIN queries ?

DAIRAV
  • 701
  • 1
  • 6
  • 29
sunil bhardwaj
  • 119
  • 1
  • 4
  • And your code is? https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/ – JB Nizet Nov 26 '18 at 09:53
  • What is 'almost immediately'? If you almost immediately invoke the getter of that lazy property, Hibernate will almost immediately send the additional SELECT. – Selaron Nov 26 '18 at 09:56
  • Possible duplicate of [Making a OneToOne-relation lazy](https://stackoverflow.com/questions/1444227/making-a-onetoone-relation-lazy) – Alan Hay Nov 26 '18 at 09:59
  • @JB Nizet : I have one to one with primary key in child table. Sample code is updated. – sunil bhardwaj Nov 26 '18 at 10:09
  • As explained in the linked article, the inverse side can't really be lazy unless you use bytecode enhancement. Hibernate needs to know if there is a B associated to the A, and since there is no foreign key in A (it's in B), it needs to execute a select to know if b should be null or not. – JB Nizet Nov 26 '18 at 10:13
  • So its always EAGER to make way for hibernate to know which B is associated to A. am I right ? – sunil bhardwaj Nov 26 '18 at 10:17
  • @AlanHay : I am not making one to one lazy/eager but asking the default implementation. – sunil bhardwaj Nov 26 '18 at 10:28
  • The comments and links provided surely make it pretty clear how it works. What *exactly* is your question? – Alan Hay Nov 26 '18 at 11:32

1 Answers1

0

So I have found what is the default behavior of the JPA one to one entities. They are always eager even when the fetch type is LAZY. There is no proxy created for it and one to one associations are resolved along with the parent fetch.

As suggested by another thread, Byte code instrumentation is the right way to achieve lazy resolution.

sunil bhardwaj
  • 119
  • 1
  • 4