简体   繁体   中英

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

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?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM