Jan
24
2011
@OneToOne reversemapping and lazy loading
Using JPA or especially Hibernate for mapping database tables to POJOs is quite comfortable. An essential feature here is lazy loading of constraints between objects. Unfortunately this didn’t work out of the box for reversed @OntToOne relations.
For example you have two classes:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class A { @OneToOne(fetch=FetchType.LAZY) private B foo; } public class B { @OneToOne(mappedBy = "foo", fetch = FetchType.LAZY) private A bar; public A getBar() { return bar; } } |
If you now load B from the database Hibernate needs to look if A also exists, because Hibernate needs to know if “bar” is null or not. In this case the parameter “fetch” has no effect. There are two known possible solutions to solve this problem:
- Implement the “bar” relation as @OneToMany with a collection and implement getBar as you needed. But if you need this relation in complex queries you could have problems to define the correct HQL.
- You use Bytecode instrumentation to realize a real lazy loading behaviour. In this case you have to add the following annotation to the property “bar”: @LazyToOne(LazyToOneOption.NO_PROXY)