How disable Hibernate caching for current entity without EntityManager?

Viewed 844

I have following logic:

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

How can I disable hibernate caching for this entity only in this place?

2 Answers

findById of the JpaRepository uses EntityManger.find() that will return the entity from the Persistence Context.

Unfortunately the JpaRepository does not expose EntityManager.refresh that you need to use.

So you may use the EntityManager directly and refresh the Entity.

// Inject the EntityManager
@Autowired
private EntityManager em;


// Refresh the Entity
em.refresh(savedModelEntity);

You can add annoation to your repository:

@Modifying(clearAutomatically = true)

That way, we make sure that the persistence context is cleared after our query execution.

or

@Modifying(flushAutomatically = true)

Now, the EntityManager is flushed before our query is executed.

Related