Force Hibernate to read database and not return cached entity

后端 未结 4 1279
孤独总比滥情好
孤独总比滥情好 2021-01-01 11:10

I am using Hibernate and Spring for my web application.

In database operation, Hibernate is caching entities and returning them in next request without reading the a

相关标签:
4条回答
  • 2021-01-01 11:50

    Please call EntityManger.clear() method, and then call repository.find() or repository.findOne() as per your requirement to select the updated data from database.

    @PersistentContext EntityManager em;
    @Autowired EntityReporisitory rep;
    ....
    ....
    @Transactional
    public void method(){
    ....
    ....
    em.clear();// This line will clear the current value of entity
    Entity e = rep.find(example);// In this line data will be loaded freshly from DB
    ....
    ....
    }
    
    0 讨论(0)
  • 2021-01-01 11:52
    • Call refresh entity session.refresh(entity)

      or

    • Open new session then call session2.get(EntityClass.class,id) it will pull the entity from the database

          Session session2=sessionFactory.openSession();                  
          EntityClass entity=(EntityClass) session2.get(EntityClass.class, id);
      
    0 讨论(0)
  • 2021-01-01 12:08

    session.refresh(entity) or entityManager.refresh(entity) (if you use JPA) will give you fresh data from DB.

    0 讨论(0)
  • 2021-01-01 12:10

    Do the read within a new transaction.

    For example:

    ...
    MyDTO myDTO = fetchMyDTOById(daoId);
    ...
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    private MyDTO fetchMyDTOById(Long dtoId) {
        return repository.findById(dtoId);
    }
    
    0 讨论(0)
提交回复
热议问题