hibernate - get id after save object

前端 未结 4 930
逝去的感伤
逝去的感伤 2020-12-02 20:04

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 d         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-02 20:26

    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.
    

提交回复
热议问题