1

I thought that object proxies are used only when the class has a field of Collection type, and uses Lazy fetching. But some sources seem to suggest that Hibernate 3 uses proxies for all objects regardless of whether the object has field of collection type or not.

Can someone please explain when Hibernate uses object proxies? Is it all the time, or just in some cases?

JamesENL
  • 6,400
  • 6
  • 39
  • 64
  • i'm curious as to what makes you ask this question. afaik you'll either get the actual instance (if its cached) or a proxy of it which will get hydrated when you use it. – zmf Oct 29 '14 at 04:32
  • You have to know whether there is a proxy involved or not. I think we are always working with the real object; the only thing is that if some fields are collection or association, then that real object doesn't actually have values for those fields, and is dependent on the proxy for loading those values when it becomes necessary. – Sammy Blake Oct 29 '14 at 04:50

1 Answers1

1

As per the Hibernate docs :

By default, Hibernate uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications.

So if you have a single object marked as an association (one-to-one or many-to-one) then it will be a proxy object until you try to access it, at which point Hibernate will attempt to populate it with values from the database.

AFAIK a collection will be initialized as null until you try to access it, at which point Hibernate will attempt to hydrate it with values.

As you suggest in your comment, yes, your object is entirely dependent on the proxy object to load the values when you request them.

None of this applies of course if you use fetchType.EAGER on the association. If you are new to Hibernate I suggest perusing this guide that I wrote. It covers things like fetch types and config for different types of relationships.

Community
  • 1
  • 1
JamesENL
  • 6,400
  • 6
  • 39
  • 64
  • Thanks for your reply James. So, if the object has no association (e.g. an object that has just fields of primitive types), then no proxy will be created for the object; right? –  Oct 29 '14 at 04:36
  • Yes AFAIK that is correct. In practice, if you are having to worry about if an object is a proxy or not, you might be doing it wrong. – JamesENL Oct 29 '14 at 04:47