1

What is the difference between load and get methods of Session in Hibernate?

load() will throw an unrecoverable exception if there is no matching database row.

get() will return null if there is no matching database row.

Why did Hibernate Creators kept this Method load in the API? (As it throws an unrecoverable exception if the Object isn't found). Isn't get() sufficient?

Kshitiz Sharma
  • 17,947
  • 26
  • 98
  • 169
Pawan
  • 31,545
  • 102
  • 256
  • 434
  • What do you mean by unrecoverable? Load simply throws an exception, but that can still be caught... – beny23 Jun 13 '12 at 13:23
  • Un-recoverable refers to the fact that load should be used when non-existence is a serious error (use load when you know that an instance exists) i.e. it shouldn't be used to check for existence by catching exceptions, that's what get should be used for. – Alex Barnes Jun 13 '12 at 14:23

1 Answers1

1

There is more to this that just the exception vs null return if an entity isn't found.

Load may also return you a proxy instead of a persistent instance of your entity. This proxy would then trigger the loading of this entity when a property is first accessed.

This is discussed at length on the Hibernate forums here, previously on SO here and in plenty of other places.

Community
  • 1
  • 1
Alex Barnes
  • 7,174
  • 1
  • 30
  • 50
  • Thanks Alex , the first link was very good . I still got one question here , As far as my understanding , both load and get tries to get Object from cache first , if not found then only a hit to Database is made ?? Please correct me if i am wrong . – Pawan Jun 13 '12 at 13:49
  • Yes that is correct, both method will hit the first and second level caches before going to the database. – Alex Barnes Jun 13 '12 at 14:20
  • And you should use load method only in occasions that you are certain about the existent of the object – shanika yrs May 22 '18 at 12:54