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?

2
  • 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. Commented Oct 29, 2014 at 4: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. Commented Oct 29, 2014 at 4:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.