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

廉价感情. 提交于 2019-12-01 04:57:13
Robert Petermeier

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

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

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