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

我怕爱的太早我们不能终老 提交于 2019-12-01 01:55:59

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/8945365/jpa-hibernate-proxy-not-fetching-real-object-data-sets-all-properties-to-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!