Java.Hibernate.Beginner.How do you save an object in Hibernate?

To save an object in Hibernate, you need to:
1️⃣ Open a Hibernate Session.
2️⃣ Start a transaction.
3️⃣ Call session.save() or session.persist() to make the object persistent.
4️⃣ Commit the transaction to write the object to the database.
5️⃣ Close the session to release resources.


🔹 Example step-by-step:

Session session = sessionFactory.openSession();    // 1️⃣ Open session
Transaction tx = session.beginTransaction();       // 2️⃣ Start transaction

User user = new User();                            // Create new entity
user.setUsername("alice");
user.setEmail("alice@example.com");

session.save(user);                                // 3️⃣ Save object → schedules INSERT

tx.commit();                                      // 4️⃣ Commit transaction → executes SQL
session.close();                                  // 5️⃣ Close session

🔹 What happens under the hood:
session.save(user) → assigns an ID and marks the object as persistent, adding it to the first-level cache.
✅ Hibernate queues the SQL INSERT statement in memory.
tx.commit() → triggers a flush → executes the actual SQL insert on the database.
✅ After commit, the object’s generated ID is available, and the session’s changes are persisted.

🔹 Important notes:

  • Always save objects inside a transaction → without commit(), data won’t persist to the database.
  • Remember to close the session to avoid connection and memory leaks.

🔹 Using JPA-standard persist() instead of save():

session.persist(user);  // also makes the entity persistent, but returns void

Key takeaway:
To save an object in Hibernate: open a session, start a transaction, call save() or persist(), commit the transaction, and close the session.

This entry was posted in Без рубрики. Bookmark the permalink.