java - 使用 Criteria API 和 JPQL 找到的实体是否自动位于 JPA 的持久性上下文中?

标签 java hibernate jpa jpql

我有一个关于 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, 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.

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.

注意:除了与 Java EE 相关的容器管理的持久性上下文(即:事务范围和扩展的)之外,还有应用程序管理的持久性上下文,它在范围上得到扩展并且可以在 Java EE 和 SE 环境中使用。确定您使用的是哪一个。

3.8.6 Query Execution

Query and TypedQuery methods other than the executeUpdate method are not required to be invoked within a transaction context, unless a lock mode other than LockModeType.NONE has been specified for the query. In particular, the getResultList and getSingleResult 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/

相关文章:

java - Solrcloud性能问题

java - Hibernate 可以将列的子集映射到内部子 Pojo 中

java - JPA 和装饰者模式

java - 防止 hibernate 实体更改被持久化

java - android广播接收器OnReceive()延迟导致错误

java - 参差不齐(锯齿状)数组中的行的乘积

Hibernate EntityManager.merge() 导致创建一个新实体而不是更新现有实体

java - 将 java BitSet 保存到数据库

java - 从 arm linux 上的 CMOS 相机读取流并将其转换为视频/照片

nhibernate - hibernate.default_schema 是什么意思?