hibernate - get id after save object

Hibernate

Hibernate Problem Overview


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?

Hibernate Solutions


Solution 1 - Hibernate

The session.save(object) returns the id of the object, or you could alternatively call the id getter method after performing a save.

Save() return value:

Serializable save(Object object) throws HibernateException

Returns:

the generated identifier

Getter method example:

UserDetails entity:

@Entity
public class UserDetails {
	@Id
	@GeneratedValue
	private int id;
	private String name;
    
    // Constructor, Setters & Getters
}

Logic to test the id's :

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.getTransaction().begin();
UserDetails user1 = new UserDetails("user1");
UserDetails user2 = new UserDetails("user2");

//int userId = (Integer) session.save(user1); // if you want to save the id to some variable

System.out.println("before save : user id's = "+user1.getId() + " , " + user2.getId());

session.save(user1);
session.save(user2);

System.out.println("after save : user id's = "+user1.getId() + " , " + user2.getId());

session.getTransaction().commit();

Output of this code:

before save : user id's = 0 , 0

after save : user id's = 1 , 2

As per this output, you can see that the id's were not set before we save the UserDetails entity, once you save the entities then Hibernate set's the id's for your objects - user1 and user2

Solution 2 - Hibernate

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);

Solution 3 - Hibernate

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.

Solution 4 - Hibernate

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);

Solution 5 - Hibernate

In your POJO class, give the primary key these annotations

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;

Now when you save the object, you can get the Id using the getter method that you set for id.

   session.save(stud1);
	// save the student object
	session.getTransaction().commit();
	// commit transaction
	session = factory.getCurrentSession();
	session.beginTransaction();
	// now get a new session and start transaction
	Student stud2 = session.get(Student.class, stud1.getId());
	// retrieve student based on the id: primary key
	System.out.println(stud2);
	session.getTransaction().commit();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIsabel IsadView Question on Stackoverflow
Solution 1 - HibernateChaitanyaView Answer on Stackoverflow
Solution 2 - Hibernatesaranga.awView Answer on Stackoverflow
Solution 3 - HibernateHappy PorwalView Answer on Stackoverflow
Solution 4 - HibernateRajkiran AbhivantView Answer on Stackoverflow
Solution 5 - HibernateAnshu MnnView Answer on Stackoverflow