📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
save Method
persist Method
save and persist Method Examples
Session.save() method example:
public void saveExample(Student student) {
Transaction transaction = null;
try (Session session = HibernateJavaConfig.getSessionfactory().openSession()) {
// start the transaction
transaction = session.beginTransaction();
// commit transaction
transaction.commit();
// save student entity
Serializable id = session.save(student);
System.out.println("database table id -> " + id);
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
}
Session.persist() method example:
public void persistExample(Student student) {
Transaction transaction = null;
// try with resource statement to auto close session object
try (Session session = HibernateJavaConfig.getSessionfactory().openSession()) {
// start the transaction
transaction = session.beginTransaction();
// commit transaction
transaction.commit();
// persist student entity
session.persist(student);
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
}
Summary
Feature | save() Method | persist() Method |
---|---|---|
Return Value | Returns the generated identifier | Returns void |
Behavior Outside Transaction | May insert immediately | Waits for a transaction |
Identifier Generation | Generates if not set | Generates if not set |
Guarantee of Synchronization | No specific guarantee | Ensures synchronization with the current transaction |
Use Case | When an immediate identifier is needed | Within the transaction context, no immediate identifier is needed |
Comments
Post a Comment
Leave Comment