如何在没有实体管理器的情况下禁用当前实体的休眠缓存?



我有以下逻辑:

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());

如何仅在此位置禁用此实体的休眠缓存?

JpaRepositoryfindById使用将从持久性上下文返回实体的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)

现在,在执行查询之前刷新实体管理器。

最新更新