我们正在开发一个小型网络(将在 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/