I'm using Hibernate with JPA and have a relationship that looks like this:
public class PencilImpl implements Pencil {
@ManyToOne(targetEntity = PersonImpl.class, fetch = FetchType.LAZY)
@JoinColumn(name = "owner", nullable = false)
private Person owner;
...
@Override
public final Person getOwner() {
return owner;
}
}
Since I started using the LAZY fetch type, everytime I try to get a pencil's owner (pencil.getOwner) I get a non-null object that has all of it's inner properties set to null.
I looks like the proxy created by Hibernate is not fetching the real object from the database when it should.
Any ideas? Thanks :)
This is simply how Hibernate implements lazy loading. It will give you a proxy object instead of an instance of your entity class. When you say
a non-null object that has all of it's inner properties set to null
that is probably what you saw in a debugger, right? You don't have to worry about that, once you access any of those properties via code or via a call inside the debugger, Hibernate will load the data from the DB in the background, construct an instance of your entity class and all calls to the proxy object will be delegated transparently to the actual entity. So normally, and ideally you don't have to care about the distinction Hibernate proxy <-> entity object.
I can think of two reasons to be aware of that distinction anyway:
instanceof
and casts. Read this SO question on how to test if an object is a Hibernate proxy and how to convert it to the real entity objectAs JB Nizet suggested, the final modifier in my classes' getters was messing with the proxies hibernate creates for lazy loaded relationships.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With