Java.Hibernate.Beginner.What is the difference between save() and persist() in Hibernate?

🔹 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:

Aspectsave()persist()
Return valueReturns generated IDReturns nothing (void)
TransactionWorks without one (but not recommended)Requires active transaction
APIHibernate-specificStandard JPA
BehaviorCan leave entity transientEnsures 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.
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.