It's not a secret anymore!
The moose likes Object Relational Mapping and the fly likes Hibernate: save and retrieve immediately Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Hibernate: save and retrieve immediately" Watch "Hibernate: save and retrieve immediately" New topic

Hibernate: save and retrieve immediately

Mohit Sinha
Ranch Hand

Joined: Nov 29, 2004
Posts: 125
Hi there,

I have a particular requirement where in I need to insert data into a table via Hibernate and fetch it back immediately. Typically (correct me if I am wrong) in Hibernate there is 1 operation for insert and then a subsequent operation for fetch. I want to somehow chain these 2 operations into one transaction such that the session which inserts the record gets its record back and not of some other operator's session.
currently I am inserting one record and then based on a query which picks the latest record fetch the data back. This works fine in a single user model but when simultaneous users start using this application I want to avoid users getting wrong data.
example) I enter a record for policyname='sss' and version='1'.in the database a unique id is attached for this run (say runid=22). I need this data back.
Now multiple users can work on the same policyname='sss' and version='1' at the same time so its quiet possible the runid they get may be not the appropriate ones.
Do post your thoughts on the same.
Janus Engstrøm
Ranch Hand

Joined: Nov 01, 2006
Posts: 44
Hi Mohit,

It's not possible to change the way you retrieve the inserted row? Currently, you're fetching the just inserted row by selecting the row with the highest roleID, right? When you persist your data, the runID field is automatically set by Hibernate, so you can retrieve the row by that ID:


k.siva prasadreddy

Joined: Sep 10, 2008
Posts: 5
If you want to get the saved object immediately you can use session.merge(object), which returns the inserted objected.

K. Siva Prasad Reddy.
Mohit Sinha
Ranch Hand

Joined: Nov 29, 2004
Posts: 125

Thanks for your suggestions. With regards to the runid in this case is being inserted by an ORacle sequence in the backend.

I agree. Here's the link:
subject: Hibernate: save and retrieve immediately
It's not a secret anymore!