aspose file tools*
The moose likes Object Relational Mapping and the fly likes Identity of hibernate entity being retrieved Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Identity of hibernate entity being retrieved" Watch "Identity of hibernate entity being retrieved" New topic
Author

Identity of hibernate entity being retrieved

dave taubler
Ranch Hand

Joined: May 15, 2001
Posts: 132
Hi,

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.


Dave Taubler<br />Specializing in <a href="http://taubler.com/articles/" target="_blank" rel="nofollow">Java and Web Development</a>
 
 
subject: Identity of hibernate entity being retrieved