Chủ Nhật, 27 tháng 8, 2017

Stupid mistake with jpa cache

Mất vài ngày để ngâm cứu một lỗi thật là vớ vẩn chỉ vì không test kỹ với real data trong mysql database.
Cụ thể là tình huống như sau.
 @Test
 @Transactional
 public void testCache(){
  EntityManagerFactory emf = postDAOJpa.getEntityManager().
getEntityManagerFactory();
  Cache cache = emf.getCache();
  
  Post post = postDAOJpa.find(12L);
  assertTrue(post!=null && post.getId()>0);
  if(!cache.contains(Post.class, post.getId())){
   fail("cache does not contain");
  }
  post = postDAOJpa.find(post.getId());
  Post postInsert = createPost();
  postDAOJpa.save(postInsert);
  post = postDAOJpa.find(postInsert.getId());
  assertTrue(postInsert!=null && postInsert.getId()>0);
  if(!cache.contains(Post.class, post.getId())){
   fail("cache does not contain post which is inserted in the same transaction");
  }
  
 }
test fail:cache does not contain with post insert in the same transaction.
Vấn đề là mãi sau này, mình mới test thử với dữ liệu thật thì thấy cache hoặc động bình thường.
Còn với data chỉ có trên grid data phase, thì cache sẽ bị fail.

Quả thật là kinh nghiệm xương máu. Mất khoảng vài ngày cho cái lỗi. :(:(
Cũng vui vì cuối cùng cũng solved problem.