How do I get the auto-generated id in Hibernate 7?
I have an entity with
@Id @GeneratedValue(strategy=jakarta.persistence.GenerationType.IDENTITY) public int id;
How do I create an object of this type and get the id?
In Hibernate 5/6, I could use session.save
and that would write the id value back to the id field in my object.
But in Hibernate 7, session.save
has been replaced with session.persist
, which doesn't write the id back to the object before it returns. So what do I do if I need the auto-generated id without committing the transaction?
In Hibernate 7, you're correct that session.persist()
is now preferred over session.save(), but there's an important distinction between the two:
session.persist(entity)
does not return the generated ID or trigger it immediately.session.save(entity)
(used in Hibernate 5/6) would return the generated ID and populate the entity’s @Id
field immediately.The Problem:
In Hibernate 7, using persist()
does not guarantee immediate ID generation. The ID is usually assigned during the flush, which typically happens:
session.flush()
is explicitly called.The Solution:
If you want to get the auto-generated ID before committing the transaction, you need to manually trigger a flush:
MyEntity entity = new MyEntity();
session.persist(entity);
session.flush(); // Triggers insert, and ID gets generated
int id = entity.getId();
Now entity.getId()
will return the auto-generated ID from the database.
Why the Change?
Hibernate 7 emphasizes JPA compliance, and persist()
is a JPA standard that defers database interaction until flush time. save()
was a Hibernate-specific shortcut that tightly coupled ID generation with method return — convenient, but not portable.
Summary
session.persist(entity)
to store the entity.session.flush()
if you need the ID before committing.