• 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 ...
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
  • Mikalai Zaikin

Identity of hibernate entity being retrieved

Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I'm trying to minimize trips to the database (aren't we all?) My scenario is that I have an entity of type MyObject that I am retrieving as part of a composition of another object. In other words, the MyLargeCompositeObject instance that I am retrieving contains an instance of MyObject. Later on (but in the same transaction/session) I want to update fields in MyObject and then persist those updates.

The unfortunate twist is that at that point, I no longer have a reference to the instance of MyObject that I retrieved from the database.

However, my understanding is that Hibernate's session cache still contains that instance. So I tried a little experiment. My experiment kind of worked, but also provided an unusual result. So I'm hoping someone can explain what is happening.

The clip below is part of the method I use to once again obtain a reference to the MyObject, so that I can update its fields and persist it. ("id" is a Long representing the primary key of the MyObject that I want).

When executes, Hibernate logs SQL activity, so I know it's hitting the database. That's not what I want. So then I added a test line to see if I could get a reference without hitting the database, by using load() rather than executing a query:

My experiment worked; Hibernate appeared to retrieve the ob2 object from the session cache, rather than hitting the database. But I left the other code in place as well, and so Hibernate then hits the database to get another instance of the MyObject entity. Except... the instance is actually the same one via the load() method.

So... does anyone know what Hibernate is doing here? Or am I mis-interpreting something? Thanks in advance.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    Bookmark Topic Watch Topic
  • New Topic