持久化文件(persistence.xml)中不同的transaction-type属性

77

在 persistence.xml JPA 配置文件中,您可以有以下一行:

<persistence-unit name="com.nz_war_1.0-SNAPSHOTPU" transaction-type="JTA">

或者有时候:

<persistence-unit name="com.nz_war_1.0-SNAPSHOTPU" transaction-type=”RESOURCE_LOCAL”>

我的问题是:

transaction-type="JTA"transaction-type="RESOURCE_LOCAL"之间有什么区别?

我还注意到一些缺少事务类型的persistence.xml文件,这样做正确吗?

1个回答

127

默认值

在JavaEE环境中默认为 JTA,在JavaSE环境中默认为 RESOURCE_LOCAL

RESOURCE_LOCAL

使用 <persistence-unit transaction-type="RESOURCE_LOCAL">,你需要负责创建和跟踪EntityManagerPersistenceContext/Cache)。

  • 必须使用EntityManagerFactory获取EntityManager
  • 所得到的EntityManager实例是一个PersistenceContext/Cache
  • EntityManagerFactory只能通过@PersistenceUnit注解进行注入(不能用@PersistenceContext
  • 不允许使用@PersistenceContext引用类型为RESOURCE_LOCAL的单元
  • 每次调用EntityManger都必须使用EntityTransaction API开始/提交事务
  • 调用entityManagerFactory.createEntityManager()两次将产生两个单独的EntityManager实例和两个单独的PersistenceContexts/Caches
  • 除非你已经销毁第一个EntityManager否则几乎从不使用多个EntityManager实例(不要创建第二个实例)

JTA

使用 <persistence-unit transaction-type="JTA">,容器将执行EntityManagerPersistenceContext/Cache)的创建和跟踪。

  • 不能使用EntityManagerFactory获取EntityManager
  • 只能获得容器提供的EntityManager
  • EntityManager只能通过@PersistenceContext注解进行注入(不能用@PersistenceUnit
  • 禁止使用@PersistenceUnit来引用JTA类型的单元。
  • 容器提供的EntityManager是一个对关联JTA事务的PersistenceContext/Cache的引用。
  • 如果没有进行JTA事务,则无法使用EntityManager,因为不存在PersistenceContext/Cache
  • 所有在同一事务中引用相同单元的EntityManager持有者将自动引用相同的PersistenceContext/Cache
  • PersistenceContext/Cache会在JTA提交时被刷新和清空。

  • 1
    你可以在JavaSE环境中使用JTA,并从EMF自己获取EM……例如在使用独立的JTA提供程序时。也许你的列表是指JavaSE和JavaEE,而不是JTA和RESOURCE_LOCAL。 - DataNucleus
    5
    “同时使用多个EntityManager实例几乎从来都不是一个好主意”-- 这是你的观点吗?在并发应用程序中经常需要打开多个EntityManager实例。总体而言,这是一个非常好的答案。 - Samuel
    1
    我使用了RESOURCE_LOCAL,而不需要自己开始和结束事务。我认为RESOURCE_LOCAL更像是“我想使用本地测试内存来测试这个数据库”,这对于JUnit测试非常有帮助。 - ha9u63a7
    2
    我不同意“您不允许使用@PersistenceUnit引用JTA类型的单元”的说法。我认为您可以轻松地这样做,并且可以使用方法emf.createEntityManager()来获取实体管理器。您可以使用类型为SynchronizationType的参数来定义当前事务是否应立即加入,或者在调用em.joinTransaction()方法时自己加入它。 - chalda
    4
    好的,我会尽力进行翻译。以下是需要翻译的内容:You may take a look at the source of the answer with additional information and short example: http://tomee.apache.org/jpa-concepts.html - Radium
    显示剩余5条评论

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接