To the best of my knowledge, creating a dynamic Java proxy requires that one have an interface to work against for the proxy. Yet, Hibernate seems to manage its dynamic proxy generation without requiring that one write interfaces for entity classes. How does it do this? The only clue from the Hibernate documentation refers to the fact that classes must have at minimum a package-visible constructor for proxy generation.
Is Hibernate doing runtime bytecode engineering with a custom classloader? The documentation suggests that this is not the case. So how do they create their proxy wrappers around the concrete entity objects? Do they just create a proxy of some trivial interface without concern for type safety and then cast it as desired?
By definition, a proxy is “a function authorized to act as the deputy or substitute for another”. This applies to Hibernate when we call Session. load() to create what is called an uninitialized proxy of our desired entity class. This subclass will be the one to be returned instead of querying the database directly.
getStreet() , Hibernate will hit the database to fetch the values for the associated entity and initialize it. Hibernate also returns a proxy object when you ask for an entity using the load method instead of the get method of the Session class.
JDK dynamic proxy is available with the JDK. It can be only proxy by interface so target class needs to implement interface. In your is implementing one or more interface then spring will automatically use JDK dynamic proxies. On the other hand, CGLIB is a third party library which spring used for creating proxy.
The JPA lazy loading mechanism can either be implemented using Proxies or Bytecode Enhancement so that calls to lazy associations can be intercepted and relationships initialized prior to returning the result back to the caller.
Since Hibernate 3.3, the default bytecode provider is now Javassist rather than CGLib.
Hibernate Core Migration Guide : 3.3
Hibernate uses the bytecode provider configured in hibernate.properties
, for example:
hibernate.bytecode.provider=javassist
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With