[hibernate] hibernate - get id after save object

Because of an purpose, I need to get an id of an object right after an insertion. I can work around with this code:

 session.save(Object o)   // insert to database
 findByPorperty( o.property ) // Return the inserted object along with the id

I think the above code is not sufficient because the session need to reopen to find the object. So:

  1. Is there a better way obtain the id?
  2. If there is, can I apply the same strategy to obtain a list of ids after inserting a bag of object?

This question is related to hibernate

The answer is


By default, hibernate framework will immediately return id , when you are trying to save the entity using Save(entity) method. There is no need to do it explicitly.

In case your primary key is int you can use below code:

int id=(Integer) session.save(entity);

In case of string use below code:

String str=(String)session.save(entity);

Let's say your primary key is an Integer and the object you save is "ticket", then you can get it like this. When you save the object, a Serializable id is always returned

Integer id = (Integer)session.save(ticket);

or in a better way we can have like this

Let's say your primary key is an Integer and object you save is "ticket", then you can get it like this. When you save the object, id is always returned

//unboxing will occur here so that id here will be value type not the reference type. Now you can check id for 0 in case of save failure. like below:

int id = (Integer) session.save(ticket); 
if(id==0) 
   your session.save call was not success. 
else '
   your call to session.save was successful.