3

I want to know how things work inside Hibernate.

So, I have a person in DB whoes name is "Peter";

Session session = SessionFactory.openSession();
Person p = session.get(Person.class, 1);//Peter's id is 1
System.out.println(p.getName());//output : Peter
p.setName("Joey");
session.flush();
session.close();

And now this person's name in DB have changed to "Joey".

How did that happened?

when I changed the person's name. How did hibernate detected the changes?

Joey
  • 228
  • 1
  • 2
  • 11
  • @SajanChandran how ,when did hibernate detect that? – Joey May 19 '14 at 09:39
  • This link explains [how](http://stackoverflow.com/questions/5268466/how-does-hibernate-detect-dirty-state-of-an-entity-object) hibernate detects the changes and execute appropriate queries. – Sajan Chandran May 19 '14 at 09:41

2 Answers2

2

The Session#flush() method makes the data that is currently in the session synchronized with what is in the database.

According to the javadoc:

Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
1

Notice that you used the method session.get (refer to the doc ) and this in turn return a persistent instance,

Persistent instances are tracked by the Hibernate session and changes are persisted to the database at session flush time. Therefore if you made changes to a persistent instances, those changes will be propagated to database on session flush

Persistent entities are detached from the session via Session.evict(), Session.clear() and Session.close() calls.

Ashish
  • 510
  • 3
  • 14
  • Are you sure that `session.flush()` make underlying db changes? I think, after `flush()`, the changes are still as Uncommitted changes, and real changes will be at commit time. You can inspect db with SQL command after `flush` but not before `commit`. – Wundwin Born May 19 '14 at 09:48
  • This is the default hibernate behaviour, unless specified otherwise in the flush mode http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/FlushMode.html – Ashish May 19 '14 at 09:54