Hibernate Lazy loading not work in OneToOne relation

4.6k Views Asked by At

In my company we migrated one old app from Hibernate 2 to Hibernate 4. My task was to move all xml entities to annotations. After moving it lazy loading in OneToOne relationship stop working.

entity a xml:

<id name="entityAid" type="integer" column="entityAid_id">
<one-to-one name="entityB" entity-name="EntityB"
        property-ref="entityA" />

entity b xml:

<property name="entityAid" type="integer" column="entityA_id" />
<many-to-one name="entityA" column="entityA_id" entity-name="EntityA" update="false" insert="false" />

I moved it with code:

entity a

 @OneToOne(fetch = FetchType.LAZY, mappedBy = "entityA")
 private EntityB storageRatecard;

entity b

@ManyToOne
@JoinColumn(name = "entityA_id", insertable = false, updatable = false)
private EntityA entityA;

Now when I run app lazy loading not work but worked on xml conf. I found:

Making a OneToOne-relation lazy

but nothing helps.(I cant use bytecode instrumentation)

What I am doing wrong? Why with xml everything is ok and with annotations no?

3

There are 3 best solutions below

0
On BEST ANSWER

What work for mi is Lazy one-to-one inverse relationships.

I read about this here (it is also a good tutorial how to use it). I hope it will help some one as it helps me.

4
On

Change from:

@OneToOne(fetch = FetchType.LAZY, mappedBy = "entityA")
private EntityB storageRatecard;

to :

@OneTOMany(optional = false, fetch = FetchType.LAZY, mappedBy = "entityA")
private List<EntityB> storageRatecard;

Or if you want to make one to one bidirectional relationship than:

From:

@ManyToOne
@JoinColumn(name = "entityA_id", insertable = false, updatable = false)
private EntityA entityA;

to:

@OneToOne
@JoinColumn(name = "entityA_id", insertable = false, updatable = false)
private EntityA entityA;
0
On

JPA eager loads single ended association. Check the following link for more details: JPA default fetch type