4

I have a bidirectional @OneToOne relationship between A and B. A owns the relationship. So, in A.java:

@OneToOne // no need for mappedBy here because A owns this relationship
private B b;

And in B.java:

@OneToOne(mappedBy = "b") // A's "b" field owns this relationship
private A a;

What are my fetch type options here? Can they be different on each side? That is, can I specify A's relationship to eagerly fetch the associated B, while telling B to lazily fetch the associated A?

Or, related: if i put fetch = FetchType.EAGER on B#a, is it respected? Under what circumstances?

Laird Nelson
  • 15,321
  • 19
  • 73
  • 127

2 Answers2

0

Edit : removed false statement (OneToOne are always eagerly fetched)

OneToOne seems to be implemented using bytecode instrumentation. See JPA 2.0 / Hibernate: Why does LAZY fetching with "@OneToOne" work out of the box?

Seems you can't define lazy fetching on both owning and inverse side.

And For others relationship the fetch type is available for both side of a bi-directional relationship, it just tells the entityManager to retrieve also the associated object or to replace it by a proxy when retrieving the current instance.

Community
  • 1
  • 1
Gab
  • 7,869
  • 4
  • 37
  • 68
  • Could you cite a section in the JPA specification for your first sentence? I can't find where this is explained and I'd like to read the source material. – Laird Nelson Apr 30 '13 at 18:54
  • There is not you're right. I don't know why i was about sure of that. – Gab Apr 30 '13 at 19:01
0

The default fetch for OneToOne and ManyToOne is EAGER, for OneToMany, ManyToMany and ElementCollection it is LAZY.

You can configure the fetch on either side of a mappedBy with whatever setting you desire, either both LAZY, both EAGER, or a mix.

In general, I would recommend always using LAZY. If you need something fetched, it is better to specify it at the query level, as you may not always need it.

How LAZY is implemented depends on the JPA provider. For EclipseLink byte-code weaving is used, and requires the usage of an agent in Java SE. In Java EE it works by default (on compliant Java EE servers). You can also use static weaving. Spring also allows for JPA weaving in Java SE without using an agent.

James
  • 17,965
  • 11
  • 91
  • 146