starting the transaction after persist in hibernate

I am new to JPA and Hibernate. I was testing its transaction management last evening and noticed something. I was able to persist the entity even though I started the transaction after calling save method and also if I don’t commit the transaction, its doesn’t persist. I am so confused about the workflow of the hibernate transaction. Here is the code snippet:

 Session session = sessionFactory.openSession();
 firstUser  = createUser("aaa@aa.com", "a", "yyy", true);
 session.save(firstUser);
 session.beginTransaction().commit();

Changes that are flushed to a database withing one session/transaction are only visible to other sessions/transactions if the transaction which did the changes also committed, that’s just how things work.

I was able to persist the entity even though I started the transaction after calling save

Hibernate has a mode where it defers flushing to the database until the transaction commits instead of immediately. I guess your model simply allows deferring the flush and that’s why you are seeing this.

then how my entity (which I saved) is aligned with the transaction? whats the role of the transaction in this case as entity is not persisting without commit.

If you don’t even understand the most basic concepts like a database transaction, you maybe shouldn’t start learning this on the fly by using Hibernate. Buy a book about SQL first so you understand the basics.