Today I met the issue about EntityManager cache issue.
Let's say that I have 2 tables comment and commant_like. I have a database trigger which increment the field like_count of comment when inserting one new comment_like record.
Below is the orignal code looks like:
In my expectation, the save call will make the database trigger to update the like_count in the comment, but it doesn't.
public void addLikeOnComment(...) {
commentLikeDao.save(newEntity);
Comment comment = commentDao.find(id);
}
After digging into the code, I found the find has been called somewhere before addLikeComment. so the entity manager will use the cached version message.
public void doWork(...) {
commentDao.find(id);
addLikeOnComment(...);
}
The solution is simple. Use the entity manager refresh, to load data from database instead of the cached version
public void addLikeOnComment(...) {
commentLikeDao.save(newEntity);
Comment comment = commentDao.find(id);
commentDao.getEntityManager().refresh(comment)
}
-- EOF --
No comments:
Post a Comment