Issue
Can anyone tell me what's the advantage of load()
vs get()
in Hibernate?
Solution
Whats the advantage of load() vs get() in Hibernate?
load() | get() |
---|---|
Only use load() method if you are sure that the object exists. |
If you are not sure that the object exist, then use one of get() methods. |
load() method will throw an exception if the unique id is not found in the database. |
get() method will return null if the unique id is not found in the database. |
load() just returns a proxy by default and database won't be hit until the proxy is first invoked. |
get() will hit the database immediately. |
Proxy means, hibernate will prepare some fake object with given identifier value in the memory without hitting a database.
For Example:
If we call session.load(Student.class,new Integer(107));
hibernate will create one fake Student object [row] in the memory with id 107, but remaining properties of Student class will not even be initialized.
Answered By - Premraj