Hodglem Hodglem - 1 year ago 73
Java Question

Consequnces of Not Commiting a Hibernate Select Transaction

I am new to Hibernate and have inherited a code base that uses it. Auto-commit is not defined so it is by default false. Based on other questions I have asked though, answers have indicated that best practice is to demarcate the code such that if you begin a transaction you should always commit() or rollback() (Thanks to Apostolos).
This code base uses the format in the below code for Select statements. I intend to properly demarcate any new code to commit() or rollback(), but I am just curious what the consequences would be for using the below model.The application has and continues to work alright, but I want to understand if there is any trouble with the existing code.

this.session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
entityReturned = (MultipleKeyTable) session.get(MultipleKeyTable.class, entityId);

Answer Source

Session.close() "End[s] the session by releasing the JDBC connection and cleaning up" (Hibernate SharedSessionContract docs). That's not as explicit as I might like, but every plausible interpretation I can think of for "releasing the JDBC connection" implies ending any open transaction one way or another. Still, just closing the session instead of explicitly ending the transaction is at best sloppy.

For what it's worth, the Session docs recommend this idiom:

Session sess = factory.openSession();
Transaction tx = null;
try {
    tx = sess.beginTransaction();
    //do some work
catch (Exception e) {
    if (tx!=null) tx.rollback();
    throw e;
finally {

If desired, you can run multiple transactions in the same session before closing it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download