7

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

juanedi
  • 233
  • 2
  • 8
  • 4
    Are you calling the getters and getting null? Or are you inspecting the object in a debugger? If the former, try removing the final modifier on your getters. If the latter, try actually calling getters. – JB Nizet Jan 20 '12 at 17:29
  • See also http://blog.bolkey.com/2009/05/hibernate-datanucleus-r1/ – DataNucleus Jan 21 '12 at 08:12

2 Answers2

7

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
Community
  • 1
  • 1
Robert Petermeier
  • 3,972
  • 4
  • 26
  • 37
  • 4
    Thank you Robert. The problem here is that the proxy is actually not doing what it's supposed to do. Calls to the proxy's getters return null. – juanedi Jan 20 '12 at 18:03
2

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

juanedi
  • 233
  • 2
  • 8