How to write to multiple tables in JPA in a single transaction?

610 Views Asked by At

I would like to know how to update data into 2 tables in a single transaction in JPA. I am using Eclipse and the JPA tool generates code to update each table wrapped in its own transaction. Following is the generated code.

TABLE1

@Action(Action.ACTION_TYPE.UPDATE)
public void updateTable1(Table1 table1) throws Exception {
    EntityManager em = getEntityManager();
    try {
        utx.begin();
        em.joinTransaction();
        table1 = em.merge(table1);
        utx.commit();
    } catch (Exception ex) {
        try {
            utx.rollback();
        } catch (Exception e) {
            ex.printStackTrace();
            throw e;
        }
        throw ex;
    } finally {
        em.close();
    }
}

TABLE2

@Action(Action.ACTION_TYPE.UPDATE)
public void updateTable2(Table2 table2) throws Exception {
    EntityManager em = getEntityManager();
    try {
        utx.begin();
        em.joinTransaction();
        table1 = em.merge(table2);
        utx.commit();
    } catch (Exception ex) {
        try {
            utx.rollback();
        } catch (Exception e) {
            ex.printStackTrace();
            throw e;
        }
        throw ex;
    } finally {
        em.close();
    }
}

With above code I can call

updateTable1(table1);
updateTable2(table2);

I would think if the second call fails the update of table1 would still happen. I am thinking I would not be able to use the generated code and would need to write my own function that would wrap both updates in one transaction. What is the right way to do this?

1

There are 1 best solutions below

0
shockwave On

Try doing this :

try {
    utx.begin();
    em.joinTransaction();
    table1 = em.merge(table1);
    table2 = em.merge(table2);
    utx.commit();
} catch (Exception ex) {
    try {
        utx.rollback();
    } catch (Exception e) {
        ex.printStackTrace();
        throw e;
    }
    throw ex;
} finally {
    em.close();
}