Hibernate Session – get() vs load()

Both these methods create a object representing the row with a given id. For example
MyClass myObj = session.get(MyClass.class, rowId)
MyClass myObj = session.load(MyClass.class, rowId)

But what’s the need for having 2 methods which perform same function?
There isn’t actually, except when both the methods have slight difference in behavior. The load() method always returns an object, actually a proxy object, with the rowId property id set to rowId. It does not hit the database to get the object. As soon as you try to get any property like employeeCode ( by calling getEmployeeCode() ), it hits the database. If at this point the rowId does not exist then it will throw an exception – ObjectNotFound.

The get() method actually hits the database as soon as you make a call and gets the object representation for the row with id equal to rowId. If the row with the given id is not found then null is returned.

If you have a function which returns object with a given id then use get(), but if you only need one or two properties from the row then you can use load().

Happy Hibernating,

Software Engineer
Sollogics Software Technologies