我有以下逻辑:
ModelEntity savedModelEntity = modelEntityRepository.save(modelEntityForSave);
//saving collection to entity here
ModelEventEntity modelEventEntity = prepareModelEventEntityForSave(savedModelEntity);
modelEventRepository.save(modelEventEntity);
//this modelEntity is cached
ModelEntity modelEntity = modelEntityRepository.findById(savedModelEntity.getId());
如何仅在此位置禁用此实体的休眠缓存?
JpaRepository
findById
使用将从持久性上下文返回实体的EntityManger.find()
。
不幸的是,JpaRepository
不会公开您需要使用EntityManager.refresh
。
因此,您可以直接使用该EntityManager
并刷新实体。
// Inject the EntityManager
@Autowired
private EntityManager em;
// Refresh the Entity
em.refresh(savedModelEntity);
您可以向仓库添加注释:
@Modifying(clearAutomatically = true)
这样,我们就可以确保在查询执行后清除持久性上下文。
或
@Modifying(flushAutomatically = true)
现在,在执行查询之前刷新实体管理器。