Whenever Hibernate returns an instance of an entity class, it checks whether it can return a proxy
instead and avoid a database hit.
I wanted to understand that in the first place, how does the proxy get the unique id associated with entity object. It has to eventually come from db. right?
What if none of this is true and the object has to be fetched from database.
load() method will throw an exception if the unique id is not found in the database. So does it mean that the load API has to hit db to make sure that the id exist in db. If yes, then what does it mean that "When proxy is loaded, it does not hit db "
I found the following lines from Java Persistence with hibernate, topic 13.1.3 Understanding proxies.
My question is that how does hibernate know if there is an entry for Item with Id 123 in database table without actually hitting the database.
Proxies are placeholders that are generated at runtime. Whenever Hibernate
returns an instance of an entity class, it checks whether it can return a proxy
instead and avoid a database hit. A proxy is a placeholder that triggers the loading
of the real object when it’s accessed for the first time:
The third line in this example triggers the execution of the SQL that retrieves an
Item into memory. As long as you access only the database identifier property, no
initialization of the proxy is necessary. (Note that this isn’t true if you map the
identifier property with direct field access; Hibernate then doesn’t even know that
the getId() method exists. If you call it, the proxy has to be initialized.)
As long as I'm doing a item.getId(), I don't have to go to the database right?
Only when you're doing, item.getDescription(); we actually need some data which is not in any of the cache and hibernate has to fire a SQL and fetch the information.
Now, where are you confused?
If you are not laughing at yourself, then you just didn't get the joke.