• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to get inserted ID in hibernate?? thanks

 
Like Zhang
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just wonder if there is any easy method to get the id for an inserted object. For example I want to have some method like this:
public int addElement(Object obj); //return the id of inserted object

How to do this?? Thanks.
 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i'd iterate the collection, retrieve the just added object, get its Id and then return it
 
Lasse Koskela
author
Sheriff
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's no need to iterate if you just keep the reference to the object you added. Consider this pseudo-code:

Now, in this example, if the mapping document for Car specifies a collection of tires and that association has cascade="all" (for example), the last statement there does the following:
1) update the Car object's data to database
2) assign an id for the Tire object we just created and save it to database
3) update the association table to associate 'tire' with 'car'

In other words, after the above code snippet is executed, the Tire object is stored in the database and the object has an id -- which you can query with a simple getter.
 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In other words, after the above code snippet is executed, the Tire object is stored in the database and the object has an id -- which you can query with a simple getter.

using your own words: in other words, your explanation was perfect
thanks a lot
 
Lasse Koskela
author
Sheriff
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, the explanation could've been simpler still without the cascade/association stuff in the mix:
 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i wonder why sometimes one uses transaction and other times session.flush():
Session s;
Transaction t;
do something
t.commit();

but you use:
...
do something
s.flush();
is there any relevant reason for that?

i read here the following:
If you happen to be using the Transaction API, you don't need to worry about this step. It will be performed implicitly when the transaction is committed. Otherwise you should call Session.flush() to ensure that all changes are synchronized with the database.
but which is better, or, is there any relevant criteria for using one in preference for another?
i'm using MySql standard in a stand alone app
[ March 09, 2005: Message edited by: miguel lisboa ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic