javahibernatehibernate3

two transaction issue with Hibernate 3


In our application we are using Hibernate 3. Recently I faced one issue in transactions. I have some code in following manner

    method1()
    try{
    tx = session.beginTransaction();
    //New object which needs to be stored
    session.save(object);
    // Some code which generates exception
    tx.commit(); // Exception occured before commit processing
    }catch(Exception ex){
    e.printStackTrace();
    throw e;
    }finally{
    if(tx!=null && tx.wasNotCommited()){
    tx.rollback();
    }
    }

I have another method same as this, which is called after this method even in case of exception is thrown from this method.

Session is same across both of the method.

Now what I am experiencing is if my 2nd method executes successfully and commits hibernate transaction, this stores data which has been saved in 1st method which I don't want.

I can not share exact code, but prepared one Test method which is similar to this issue. My database server is mysql.

package com.opshub.jobs.core;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.opshub.dao.core.Company;
import com.opshub.utils.hibernate.HibernateSessionFactory;

public class Test {

    public static void main(String[] args) throws Exception{
        Session session = HibernateSessionFactory.openSession();
        try{
            Transaction tx = session.beginTransaction();
            try{
                Company company = new Company();
                company.setName("Gaurav");
                company.setCompanyDetails("IT Company");
                company.setCompanyAddress("India");
                session.save(company);
                if(true)
                    throw new Exception("Now go to finally");
                tx.commit();
            }catch(Exception e){
                throw e;
            }finally{
                tx.rollback();
            }
        }finally{
            Transaction tx = session.beginTransaction();
            tx.begin();
            Company company = new Company();
            company.setName("Gaurav 1");
            company.setCompanyDetails("IT Company");
            company.setCompanyAddress("India");
            session.save(company);
//          if(true)
//              throw new Exception("Now go to finally");
            tx.commit();
        }
    }

}

Any help would be appreciated.


Solution

  • Finally I found the solution to this issue. Before starting another transaction/operations you can use session.clear() which removes all the pending save/update/delete operation from the session.

    So in finally with rollback, just add session.save().

    Thanks for your responses.