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})
@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: