Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA/Hibernate proxy not fetching real object data, sets all properties to null

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

like image 706
juanedi Avatar asked Jan 20 '12 17:01

juanedi


2 Answers

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:

  1. Performance: when you access the elements of a lazily loaded collection in a loop, lazy loading can really slow down your app
  2. Inheritance: if your data model uses inheritance, be very careful with 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 object
like image 87
Robert Petermeier Avatar answered Oct 27 '22 00:10

Robert Petermeier


As JB Nizet suggested, the final modifier in my classes' getters was messing with the proxies hibernate creates for lazy loaded relationships.

like image 41
juanedi Avatar answered Oct 26 '22 23:10

juanedi