Java.Hibernate.Beginner.When i say save, is it saved to cache ?

When you call save() on an entity, does it save to the cache or the database?

Answer:
When you call session.save(entity) in Hibernate:

🔹 1) First, it saves the entity to the session’s first-level cache:

  • The entity becomes persistent: Hibernate starts tracking it.
  • The Session maintains an in-memory cache of persistent entities, called the first-level cache.
  • At this point, the entity’s state is not yet immediately written to the database.

🔹 2) Then, at flush() or transaction commit(), Hibernate writes changes to the database:

  • Hibernate will automatically generate SQL INSERT or UPDATE statements for all persistent entities with changes.
  • flush() synchronizes the session’s in-memory state with the database.

🔹 Example:

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

User user = new User();
user.setUsername("john");

session.save(user); // user is now in the first-level cache, not yet in DB

// No SQL sent to DB yet, unless flush happens here

tx.commit(); // Hibernate flushes pending changes to DB (INSERT happens now)
session.close();

🔹 Key point about the first-level cache:

  • This cache is per-session: each Session has its own cache of entities it manages.
  • It’s mandatory in Hibernate — you cannot disable it.
  • It avoids repeated SQL queries or updates for the same entity during a session.

So:

  • session.save() → adds the entity to the session’s first-level cache.
  • Only on flush or commit does Hibernate actually persist the entity’s state to the database.
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.