0

PFB my code,

        try {
        entityManager = emFactory.createEntityManager();
        emTransaction = entityManager.getTransaction();



        emTransaction.begin();
            EmployeeEntity e1 = new EmployeeEntity();
            e1.setEmpId(1);
            e1.setEmpName("Dheepan");

            EmployeeEntity e2 = new EmployeeEntity();
            e2.setEmpName("Raju");

            entityManager.persist(e1);
            entityManager.persist(e2);
        emTransaction.commit();



    }catch(PersistenceException e){
        if(emTransaction!=null && emTransaction.isActive()){
            emTransaction.rollback();
        }
    }

empId attribute is not set in e2 intentionally so that exception will be thrown. As soon exception thrown, rollback should happen. But still I am able to see e1 got persisted into the database. Could anybody tell why rollback didn't happen?

MWiesner
  • 8,868
  • 11
  • 36
  • 70
JPS
  • 2,730
  • 5
  • 32
  • 54
  • 2
    emTransaction!=null && emTransaction.isActive Are you sure it send true? – Ahmet Karakaya Jul 25 '15 at 09:56
  • 2
    A persistence exception already marks the transaction for rollback. There is no need to call rollback directly on this transaction type, just close the EntityManager – Chris Jul 25 '15 at 15:10
  • @mmc18, transaction is not active and it's returning false. don't know why transaction is closed though exception occurred. – JPS Jul 26 '15 at 01:46
  • @chris, even if it's auto rollback, there should not be any row persisted in the database , right? but e1 is persisted in the database. – JPS Jul 26 '15 at 01:52
  • 1
    May be its not going in catch block at all. I think PersistenceException is not thrown here may be NullPointerException or something else. You could change the PersistenceException to Exception. Do you have a stacktrace ? Please provide stacktrace – Utkarsh Jul 26 '15 at 02:44
  • If there is an exception, nothing should be put in the transaction as most any exception in this code would cause either the transaction to rollback, or the commit to not get called. More detail is needed- what exception are you getting, why do you expect a PersistenceException, and how are you checking something got inserted? Maybe turn EclipseLink logging on and see the statements that get issued – Chris Jul 27 '15 at 13:24

0 Answers0