0

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?

Community
  • 1
  • 1
Krzysiek
  • 1,425
  • 4
  • 19
  • 32

3 Answers3

2

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.

Krzysiek
  • 1,425
  • 4
  • 19
  • 32
0

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;
Milkmaid
  • 1,569
  • 3
  • 22
  • 36
  • Thank you for answer.I need to have one to one bidirectional relationship. I try yours solution earlier but it not help. – Krzysiek Jun 09 '15 at 07:39
  • @ognistysztorm The main idea is to have `@OneToOne` annotations on both parameters or `@OneToMany` and `@ManyToOne` – Milkmaid Jun 09 '15 at 08:51
  • I tried use OneToOne instead ManyToOne but as I wrote lazy loading still not works. I cant understand why lazy loading work when I am using hbk.xml? – Krzysiek Jun 09 '15 at 09:44
  • It's because @OneToOne lazzy works little bit diferently [look here](http://stackoverflow.com/a/1445694/4327527) – Milkmaid Jun 09 '15 at 09:56
0

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

Community
  • 1
  • 1
codedabbler
  • 1,183
  • 6
  • 12