Monday, March 22, 2010

Hibernate Lazy OneToOne Associations

Damn, this was harder than it needed to be. I have a bidirectional one-to-one association between two objects. I want the 'owner' object (the one without mappedBy=...) to be able to lazily load the 'owned' object.


@OneToOne(optional=false, fetch=FetchType.LAZY, cascade={CascadeType.PERSIST,CascadeType.REMOVE})
@LazyToOne(LazyToOneOption.PROXY)
@JoinColumn(name = "partyAttentionId")
ChildObject childObject;


This doesn't work. Supposedly from all the forum posts I read the 'key' would be to get that optional=false in there. No joy, I'm profiling in JProfiler and it's still eagerly loading this property.

Either LazyToOneOption.PROXY isn't intended to work for OneToOne associations (I couldn't find documentary evidence of this) or it's a bug.

The only alternative is to use LazyToOneOption.NO_PROXY and run bytecode enhancement during the build as described here: http://tricksdev.blogspot.com/2009/03/hibernate-bytecode-instrumentation.html

1 comment:

  1. Got this working: Key was @Proxy(lazy=true) at the class level on the 'child' entity.

    The 'optional=false' thing is a real bummer. We have lot of optional associations and this kills performance.

    ReplyDelete