Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Hibernate create proxies of concrete classes?

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?

like image 535
Kris Nuttycombe Avatar asked Dec 24 '08 18:12

Kris Nuttycombe


People also ask

How does Hibernate proxy work?

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.

Which method returns proxy object in hibernate?

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.

How are JDK dynamic proxies?

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.

What is proxy in JPA?

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.


2 Answers

Since Hibernate 3.3, the default bytecode provider is now Javassist rather than CGLib.

Hibernate Core Migration Guide : 3.3

like image 127
Andrew Newdigate Avatar answered Sep 23 '22 19:09

Andrew Newdigate


Hibernate uses the bytecode provider configured in hibernate.properties, for example:

hibernate.bytecode.provider=javassist
like image 28
Maciek Kreft Avatar answered Sep 21 '22 19:09

Maciek Kreft