java - 应用程序管理 JPA,何时需要事务

标签 java jpa jpa-2.0

我们正在开发一个小型网络(将在 Tomcat 上运行),数据层使用 JPA (Eclipselink) 完成。 我前段时间做过类似的事情。但我总是不确定何时需要开始和结束交易或进行冲洗。 目前,如果我添加(坚持)和删除对象,我会使用事务。如果我在一个已经持久化的对象上调用 setter,我不使用事务。

是否有指南/教程或简短回答何时使用事务或如何正确实现应用程序管理的 JPA。

最佳答案

我认为可以总结出您问题的答案。 几乎所有 JPA 操作都需要一个事务,除了不锁定实体的查找/选择(即任何不更改数据的 JPA 操作)。

(JTA 事务范围的实体管理器) 对于 JTA 事务范围的实体管理器,最好引用规范(第 3 章实体操作):

The persist, merge, remove, and refresh methods must be invoked within a transaction context when an entity manager with a transaction-scoped persistence context is used. If there is no transaction context, the javax.persistence.TransactionRequiredException is thrown.

Methods that specify a lock mode other than LockModeType.NONE must be invoked within a transaction context. If there is no transaction context, the javax.persistence.TransactionRequiredException is thrown.

The find method (provided it is invoked without a lock or invoked with LockModeType.NONE) and the getReference method are not required to be invoked within a transaction context. If an entity manager with transaction-scoped persistence context is in use, the resulting entities will be detached; if an entity manager with an extended persistence context is used, they will be managed. See section 3.3 for entity manager use outside a transaction.

(应用程序管理/资源本地实体管理器) 在应用程序管理的实体管理器的情况下,JPA 规范对行为不明确。在 Hibernate 的情况下,当不在事务内时(它还可能取决于 JDBC 驱动程序和数据库连接的自动提交模式),发生的事情非常复杂。检查Hibernate's article在这个主题上。 基本上,强烈建议您始终对上述操作使用事务。

关于你问题的第二部分:如果你调用了托管实体的 setter ,并且没有刷新你分离了它(即在事务提交之前),行为是不清楚/未定义的,即你最好更正代码。

错误代码示例:

//begin Transaction
MyEntity entity = em.find(MyEntity.class, 1L);
entity.setField("New value");
em.detach();//it is not sure whether the "New value" will be persisted. To make sure it is persisted, ypu need to call em.flush() before detaching
//commit Transaction

通常如果数据库操作的顺序(与实体管理器操作的顺序不同)不重要,您可以让 JPA 实现来决定何时刷新(例如在事务提交时) .

关于java - 应用程序管理 JPA,何时需要事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21672454/

相关文章:

postgresql - 如何向 jpa/hibernate 查询提供 LocalDateTime?

java - @JoinFetch 什么都不做(EclipseLink)

java - 如何检索相关实体的有限集合?

mysql - Eclipse Virgo 注入(inject)的 JPA EntityManager 不连接到数据库

java - 如何在 Android 的根文件夹中创建文件夹

java - 在 Lucene 中处理对相对较小的索引文档的大型搜索查询

java - 限制 JPA 中集合的大小

java - 从 JOOQ 解析器结果中获取表/列元数据

java - Android 设备尺寸之间布局调整技术的比较

jsf - 如何在 JSF 转换器中使用分离实体 + 版本