What will happen if we begin transaction in hibernate, then do some transaction but do not commit it? Will it save tempervoraly or it will rollback immediately?
Thanks Chetan
As long as you don't COMMIT or ROLLBACK a transaction, it's still "running" and potentially holding locks. If your client (application or user) closes the connection to the database before committing, any still running transactions will be rolled back and terminated.
Commit will make the database commit. The changes to persistent object will be written to database. Flushing is the process of synchronizing the underlying persistent store with persistant state held in memory.
I have confirmed that after rollback we cannot commit the same transaction. Make sure another transaction is not in waiting, else it will be committed. Also don't do anything with transaction in finally block. Always use finally block to close connection , data reader etc.
Look at the following code, which accesses the database with transaction boundaries without use of commit:
Session session = sessionFactory.openSession();
session.beginTransaction();
session.get(Item.class, 123l);
session.close();
By default, in a Java SE environment with a JDBC configuration, this is what happens if you execute this snippet:
The SELECT is executed inside this JDBC transaction. The Session is closed, and the connection is returned to the pool and released by Hibernate — Hibernate calls close() on the JDBC Connection.
What happens to the uncommitted transaction?
The answer to that question is, “It depends!” The JDBC specification doesn’t say anything about pending transactions when close() is called on a connection. What happens depends on how the vendors implement the specification. With Oracle JDBC drivers, for example, the call to close() commits the transaction! Most other JDBC vendors take the sane route and roll back any pending transaction when the JDBC Connection object is closed and the resource is returned to the pool.
Obviously, this won’t be a problem for the SELECT you’ve executed, but look at this variation:
Session session = getSessionFactory().openSession();
session.beginTransaction();
Long generatedId = session.save(item);
session.close();
This code results in an INSERT statement, executed inside a transaction that is never committed or rolled back. On Oracle, this piece of code inserts data permanently; in other databases, it may not. (This situation is slightly more complicated: The INSERT is executed only if the identifier generator requires it. For example, an identifier value can be obtained from a sequence without an INSERT. The persistent entity is then queued until flush-time insertion — which never happens in this code. An identity strategy requires an immediate INSERT for the value to be generated.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With