本文介绍了JPA - 持久化对象时何时使用 getTransaction()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始在 Google App Engine 上使用 JPA.在阅读一些示例时,我注意到对象持久化的方式有一些变化.在一种情况下,我见过这样的事情:

I've recently started working with JPA on the Google App Engine. In reading some examples, I've noticed a couple of variations in the way objects are persisted. In one case, I've seen something like this:

entityManager.getTransaction().begin();
entityManager.persist(object);
entityManager.getTransaction().commit();

在其他情况下,我看不到 getTransaction() 的使用.我只是看到entityManager.persist(object).什么时候使用 getTransaction() 合适?

In other cases, I don't see the use of getTransaction(). I simply see entityManager.persist(object). When is it appropriate to use getTransaction()?

推荐答案

如果您使用容器管理的 EntityManager,那么您正在使用 JTA 事务.因此,您不需要(更准确地说 - 您不能)干扰使用 entityManager.getTransaction() 获取的 EntityManager 的事务.JTA 启动并提交您的事务.

If you use container managed EntityManager then you're using JTA transactions. Hence, you don't need to (more precisely - you can not) interfere with EntityManager's transactions fetched using entityManager.getTransaction(). The JTA starts and commits your transaction.

如果您使用应用程序管理的 EntityManager 并且不想参与 JTA 事务,那么您需要自己管理它们(称为资源本地实体管理器).

If you use application managed EntityManager and you don't want to be in part of JTA transaction, then you need to manage them for yourself (it's called a resource-local entity manager).

最典型的是,在 Java SE 环境中使用应用程序管理的 EntityManager,它与 EntityManager.getTransaction() 一起使用.

Most typically, application managed EntityManager which works with EntityManager.getTransaction() is used in Java SE environment.

您可能对 .

You might be interested in secion 7.5 Controlling Transactions from the JPA 2.0 specification.

这篇关于JPA - 持久化对象时何时使用 getTransaction()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 06:21