我正在研究将部署在J2EE
上的Weblogic
应用程序,它包含两个层次:
我将两层分开,以便能够在Java SE项目中重用Business层(作为jar lib)。
我正在使用transaction-type = JTA
让服务器管理事务,但在SE项目中我使用的是transaction-type = RESOURCE_LOCAL
所以我需要明确地开始并提交事务。
所以问题是:如果我在使用JTA
时明确启动并提交事务,是否有任何问题?
换句话说,以下两个代码之间存在巨大差异:
public void create(T entity) {
entityManager.persist(entity);
}
和
public void create(T entity) {
entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.getTransaction().commit();
}
在手动处理事务时,您应该更加谨慎。如果发生异常,为了回滚您的操作,请始终拥有安全网:
try {
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
try {
entityManager.persist(entity);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
throw e; // optional if you want to manage the exception higher up
} finally {
entityManager.close(); // optional if you also manage you EM creation manually.
}