Java.Hibernate.Beginner.In which cases entity starts to be trackable ?

An entity starts being trackable (i.e., Hibernate will dirty-check it and sync changes) when it becomes persistent — specifically, when it’s associated with an open Hibernate session.

🔹 Here are the cases when an entity becomes persistent and trackable:

1) When you call session.save(entity) or session.persist(entity)
Hibernate saves the transient entity → it becomes persistent → tracked for dirty changes.

2) When you load an entity with session.get(), session.load(), or a query

User user = session.get(User.class, 1L); // fetched entity is persistent and tracked

3) When you reattach a detached entity with session.update(entity) or session.merge(entity)

  • After reattaching, Hibernate starts tracking the entity again.

4) When an entity is associated through cascading

  • For example, if you save an Order with @OneToMany(cascade = CascadeType.PERSIST) on OrderLines, the child entities also become persistent and tracked.

🔹 When an entity is NOT tracked:
❌ If the entity is transient → newly created with new but not saved or loaded → Hibernate knows nothing about it.
❌ If the entity is detached → it was persistent, but the session is closed or the entity was evicted → Hibernate no longer tracks it.
❌ If you use a StatelessSession → entities are never tracked (no dirty checking at all).

🔹 Example of entity becoming trackable:

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

User user = new User();           // transient, NOT tracked yet
user.setUsername("john");

session.save(user);               // becomes persistent → Hibernate starts tracking
user.setEmail("john@example.com");// will be detected and auto-updated on flush

tx.commit();                      // flush triggers SQL UPDATE if needed
session.close();

An entity becomes trackable (persistent) when it’s attached to an open session, either by saving, loading, or reattaching — from that point on, Hibernate’s dirty checking automatically synchronizes changes to the database.

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