If I make a simple Respository.findOne(objectId) I get old object (not
updated one). I’ve to call Entitymanager.refresh(object) to get
updated object.
Why?
第一级缓存在会话期间处于活动状态.除非有理由返回数据库,否则将从第一级缓存中检索先前在会话上下文中检索的任何对象实体.
SQL更新后是否有理由返回数据库?好吧,正如Pro JPA 2关于批量更新语句(通过JPQL或SQL)的说明(p199):
The first issue for developers to consider when using these [bulk update] statements
is that the persistence context is not updated to reflect the results
of the operation. Bulk operations are issued as SQL against the
database, bypassing the in-memory structures of the persistence
context.
这就是你所看到的.这就是为什么你需要调用refresh来强制从数据库重新加载实体,因为持久化上下文不知道任何潜在的修改.
本书还注意到有关使用Native SQL语句(而不是JPQL批量更新)的以下内容:
■ CAUTION Native SQL update and delete operations should not be
executed on tables mapped by an entity. The JP QL operations tell the
provider what cached entity state must be invalidated in order to
remain consistent with the database. Native SQL operations bypass such
checks and can quickly lead to situations where the inmemory cache is
out of date with respect to the database.
基本上,如果您配置了二级缓存,则通过本机SQL语句更新当前缓存中的任何实体可能会导致缓存中的陈旧数据.