java - 如何使用 EntityManager 通过 id 查找实体而不在一次查询中命中缓存?

标签 java hibernate jpa entitymanager hibernate-entitymanager

我有一个关键的代码部分,我需要使用悲观锁通过 id 读取和锁定实体。

这部分代码现在看起来像这样:

MyEntity entity = entityManager.find(MyEntity.class, key);
entityManager.refresh(entity, LockModeType.PESSIMISTIC_WRITE);

它工作正常,但据我了解,如果 hibernate 的缓存中没有实体,我们将使用 2 个数据库读取事务。第一个事务通过 id 查找实体,另一个事务刷新并锁定实体。 在这种情况下是否可以只使用一笔交易?

我会想象这样的事情:

boolean skipCache = true;
MyEntity entity = entityManager.find(MyEntity.class, key, 
    LockModeType.PESSIMISTIC_WRITE, skipCache);

但是没有像skipCache这样的参数。是否有另一种方法可以使用 EntityManager 直接从数据库中按 id 读取实体?

更新:

如果实体存在于缓存中,则该查询将命中一级缓存。因此,它可能会返回过时的数据,这就是为什么不适合应阻止任何读取的关键部分:

MyEntity entity = entityManager.find(MyEntity.class, key, LockModeType.PESSIMISTIC_WRITE);

问题是关于跳过缓存而不是锁定。

最佳答案

我刚刚在 EntityManager 中找到了一个方法 getReference,它获取一个实例,该实例的状态可以被延迟获取。正如文档中所述:

Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, the EntityNotFoundException is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw the EntityNotFoundException when getReference is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open.

作为在一个查询中通过 ID 查找并锁定最新实体的可能解决方案,我们可以使用下一个代码:

MyEntity entity = entityManager.getReference(MyEntity.class, key);
entityManager.refresh(entity, LockModeType.PESSIMISTIC_WRITE);

此查询将创建一个实体(无数据库查询),然后刷新并锁定该实体。

关于java - 如何使用 EntityManager 通过 id 查找实体而不在一次查询中命中缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54259788/

相关文章:

java - Java RXTX 与 Arduino 串口通信

hibernate - JPA Criteria API where subclass - 出现错误 : Unable to resolve attribute [lastName] against path [null]

java - 如何向 Micronaut 项目添加第二个数据源?

java - SQL语法错误异常 : ORA-00932: inconsistent datatypes: expected DATE got BINARY

java - 如何按获取列排序?

java - jsp获取http错误描述

java - 从 nextLine 读取的输入不等于字符串值

java - 自由标记模板 : "Sort_by" one or other

java - Hibernate QueryException : Expected positional parameter count, 但查询不带参数

java - ErrorCounter 意外 token 在哪里 - Hibernate