0

I tested the following code to study CacheStoreMode.

All of the procedures below were executed in order after one procedure was completed. The method proceeded with a web controller.

[Thread 1 : Register and store entities in the database and second level cache]

Member member = new Member();
member.setName("original");
em.persist(member);

[DB console : Modify data on an entity]

update member set name = "changed" where member_id = 1;
/* Suppose that there is no other insert in the application, so you know that the id of the entity registered above is 1.
Because this query does not come from an application, keep in mind that the value of the second level cache has not changed, but only the value of the database has changed.*/

[Thread 2 : Get data directly from DB and refresh the second level cache.]

Member member = em.createQuery("select m from Member m where m.id = 1", Member.class)
         .setHint("javax.persistence.cache.retrieveMode", CacheRetrieveMode.BYPASS)
         .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
         .getSingleResult();

System.out.println(member.name);

[Thread 3 : Gets the entity from the refreshed second level cache.]

Member member = em.find(Member.class, 1L);
System.out.println(member.name);
// can put CacheRetrieveMode.USE to make sure that "find" gets data from second level cache, but I omitted.

So the result was this.

Thread 2 prints "changed"

and

Thread 3 prints "original"

This means that Thread2 normally fetched data from the database, but did not refresh the second level cache.

Thread3 did not fetch data from persistence context or DB. After Thread 3 started, the persistence context was initialized, and if data was taken from the DB, the data could not be "original".

I wonder if there is a problem with CacheStoreMode.REFRESH or if I misunderstand CacheStoreMode.REFRESH.

kwonryul
  • 481
  • 3
  • 10

0 Answers0