🔹 1) save()
✅ Returns the generated identifier (primary key) immediately as a Serializable
value.
✅ Works both inside and outside of an active transaction.
✅ Can leave the entity in a transient state if there’s no transaction (e.g., changes may not actually persist).
✅ Hibernate-specific → not part of the standard JPA API.
Session session = sessionFactory.openSession();
session.beginTransaction();
Long id = (Long) session.save(user); // returns the generated ID immediately
session.getTransaction().commit();
session.close();
🔹 2) persist()
✅ Does not return the ID — it’s a void
method.
✅ Requires an active transaction → throws TransactionRequiredException
if called outside of one.
✅ Is a standard JPA method → portable across Hibernate, EclipseLink, etc.
✅ Guarantees that the entity will become managed/persistent if transaction commits.
Example:
Session session = sessionFactory.openSession();
session.beginTransaction();
session.persist(user); // returns void; user becomes managed
session.getTransaction().commit();
session.close();
🔹 Key differences summarized:
Aspect | save() | persist() |
---|---|---|
Return value | Returns generated ID | Returns nothing (void ) |
Transaction | Works without one (but not recommended) | Requires active transaction |
API | Hibernate-specific | Standard JPA |
Behavior | Can leave entity transient | Ensures entity becomes persistent |
✅ Key takeaway:
- Use
persist()
for JPA-compliant, standard behavior requiring an active transaction. - Use
save()
if you need the ID immediately, but remember it’s Hibernate-specific.