• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Hibernate load() method

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a basic question about Hibernate load and get methods

I just wrote a simple Hibernate standalone application.

One table, one class, and one hbm file mapping them. Then I wrote a simple piece of Java/hibernate code to retrieve one record



What I had understood is that if we are sure that object/record is available in memory we should use the load method, or use get if one is not sure, and get will hit DB and get the record

Now since this is a standalone application, I though load would break, after all I have just started the application, memory must be empty, and load method should throw an exception, but to my surprise it worked fine, and record was retrieved, the sysout displayed the correct value. What am I missing?
 
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Both load() and get() will retrieve the entity instance from the database if required. The difference is that load() assumes the entity instance exists for the given identifier, and will throw an exception if it does't, whereas get() makes no such assumptions and will simply return null in such a case. Both methods will also only hit the database if the entity is not already associated with the session.
 
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
get() method always hits the database whereas load() method may or may not hit the database always because it returns the proxy object
 
Sheriff
Posts: 10445
227
IntelliJ IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Anindya Roy wrote:get() method always hits the database



That's not true. Like Jelle already noted, the session is first checked to see if that entity instance is already associated with the session before querying the database.
reply
    Bookmark Topic Watch Topic
  • New Topic