I'm reading the Hibernate documentation at present and I came across the following quote:
If the Session throws an exception, including any SQLException, immediately rollback the database transaction, call Session.close() and discard the Session instance. Certain methods of Session will not leave the session in a consistent state. No exception thrown by Hibernate can be treated as recoverable. Ensure that the Session will be closed by calling close() in a finally block.
This all makes sense as far as I'm concerned, but it does make me wonder what the effect of closing a session is with a transaction neither committed nor rolled back?
E.g consider the following:
session = getSessionFactory().openSession();
session.beginTransaction();
session.save(carObject);
//session.getTransaction().commit();
session.close();
With commit commented out, and no rollback called here, what is the expected behaviour of session.close()? Does it simply rollback that commit automatically, does it leave a 'hanging' transaction? etc.
(I understand this obviously wouldn't be good practice - I'm just trying to get my head around the underlying concepts a bit more.)
Hence, when the transaction is commited, the session is closed too.
Longer answer: hibernate is smart enough not to send insert/updates to the DB until it knows if the transaction is going to be committed or rolled back (although this behavior can be changed by setting a different FlushMode), in your case by calling flush you are forcing the SQL to be sent to the DB but you still have ...
Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations.
I've done a bit of digging into Hibernate:
Persistence sessions keep their life-cycle somewhat independent from JDBC connections. When you close Hibernate's Session
the connection is released. Exact meaning of "releasing connection" depends on how the connection was obtained in the first place:
sessionFactory.openStatelessSession(connection)
) you will get your connection with possibly unfinished transaction back when calling session.close()
session.close()
will usually end up in calling connection.close()
No automatic session flushing or transaction commit / rollback is made by Hibernate. The same states for the JPA's EntityManager
.
So what happens in the end depends on your connection provider / data source. With C3PO any unfinished transaction will be rolled-back when the connection is returned to the pool. On the other hand if you have managed JTA connection then the actual transaction handling might be completely out of scope to your application.
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