Saif
Saif

Reputation: 7042

Force Hibernate to read database and not return cached entity

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 actual database. I know this will reduce the load on database and improve performance.

But while this app still under construction, I need to load data from database in every request (testing reason).

Is there any way to force database read?

I became sure about the caching from this log4j message.

Returning cached instance of singleton bean 'HelloController'
DEBUG [http-bio-8080-exec-42] - Last-Modified value for [/myApp/../somePageId.html] is: -1

Upvotes: 38

Views: 56873

Answers (5)

BKaun
BKaun

Reputation: 657

You can use a counter to ensure a cache miss. The 'counter' can be any unique value generator, such as a literal counter, or a time parameter or even a UUID. Expect a negative condition to be true.

E.g:

@Query("select p from Post p where p.id = :postId and p.postedOn <> :cacheBustingTimer")
Post fetchPostById(@Param("postId") Long postId, @Param("cacheBustingTimer") LocalDateTime cacheBustingTimer);

Sample call

Post post = postRepository.fetchPostById(postIdToFetch, LocalDateTime.now().minusYear(100));

Upvotes: 0

Subhadeep Ray
Subhadeep Ray

Reputation: 969

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
....
....
}

Upvotes: 2

wild_nothing
wild_nothing

Reputation: 3023

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

Upvotes: 25

Hatem Badawi
Hatem Badawi

Reputation: 546

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

Upvotes: 4

Predrag Maric
Predrag Maric

Reputation: 24433

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

Upvotes: 35

Related Questions