繁体   English   中英

如何在单个事务中写入 JPA 中的多个表?

[英]How to write to multiple tables in JPA in a single transaction?

我想知道如何在 JPA 的单个事务中将数据更新到 2 个表中。 我正在使用 Eclipse 和 JPA 工具生成代码来更新包装在自己的事务中的每个表。 以下是生成的代码。

表格1

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

表2

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

使用上面的代码,我可以调用

updateTable1(table1);
updateTable2(table2);

我认为如果第二次调用失败,table1 的更新仍然会发生。 我想我将无法使用生成的代码,需要编写自己的函数,将两个更新都包装在一个事务中。 这样做的正确方法是什么?

尝试这样做:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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