我有一个关于 JPA 和实体管理器的问题。如果我使用实体管理器的查找方法,将加载数据库中的数据,并且实体是实体管理器持久性上下文的一部分,可以删除、修改或进行其他操作。
但是,如果使用 Hibernate 的 Criteria API 或 JPA 的 JPQL 或 Hibernate 的 HQL 从数据库加载实体,情况会怎样呢?
是实体还是实体,是通过使用来自 Hibernate 的 Criteria API 或来自 JPA 的 JPQL 或来自 Hibernate 的 HQL 创建的,自动成为实体管理器持久性上下文的完整部分,并且可以删除或修改为我用了entity manager的find方法?
这个JPQL例子是什么情况:
JPQL:
select k, kto.kontostand from Kunde k
left join fetch k.wohnort
left join fetch k.konten kto
where k. geschlecht = 'm' and kto. kontostand < 0
K 和完整的实体 kontostand 是否是实体管理器的完整部分?
非常感谢! 迈克
最佳答案
所有问题都没有单一的答案,因为这些问题取决于:
- 使用什么类型的实体管理器/持久性上下文(事务范围 或 i*extended*)
- 给定的实体管理器操作是在事务内部还是外部调用
- 给定的实体管理器操作或查询是否使用实体锁定
无论如何,我会尝试通过引用 JPA 2.0 规范来回答您的问题:
3.1.1 EntityManager Interface
The
persist
,merge
,remove
, andrefresh
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, thejavax.persistence.TransactionRequiredException
is thrown.The
find
method (provided it is invoked without a lock or invoked withLockModeType.NONE
) and thegetReference
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.
注意:除了与 Java EE 相关的容器管理的持久性上下文(即:事务范围和扩展的)之外,还有应用程序管理的持久性上下文,它在范围上得到扩展并且可以在 Java EE 和 SE 环境中使用。确定您使用的是哪一个。
3.8.6 Query Execution
Query
andTypedQuery
methods other than theexecuteUpdate
method are not required to be invoked within a transaction context, unless a lock mode other thanLockModeType.NONE
has been specified for the query. In particular, thegetResultList
andgetSingleResult
methods are not required to be invoked within a transaction context unless such a lock mode has been specified for the query. 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.
假设您使用的是 StatelessSession并使用查询预取 kto
然后你应该得到完整的 kontostand
作为分离(因此它不与任何持久性上下文相关联)。
希望对你有帮助。
关于java - 使用 Criteria API 和 JPQL 找到的实体是否自动位于 JPA 的持久性上下文中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22735266/