[英]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.