2

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?

3
  • That's not possible if you want to use the Repository because findById uses EntityManger.find that will return the entity from the Persistence Context. Unfortunately the JpaRepository does not expose EntityManager.refresh that you want to use. So you may use the EntityManager directly and refresh the Entity Commented Jun 4, 2020 at 11:54
  • Does this solve your problem? If yes I could add it as the answer Commented Jun 4, 2020 at 12:33
  • @SimonMartinelli yes, I was forced to use EntityManager. So you could add this answer. Commented Jun 5, 2020 at 8:12

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.