LazyInitializationException when trying to access detached objects left around in Redis by RedisCacheManager

懵懂的女人 提交于 2020-01-06 13:59:12

问题


I use Spring data Redis in order to cache serialized JPA entities in Redis using org.springframework.data.redis.cache.RedisCacheManager

Here is the method:

@Override
@Cacheable(value = MapCacheConfiguration.DATABASE_CACHE_NAME, key = "#root.method.name")
public Curriculum findCurriculumByMemberId(Long memberId) {
    return curriculumRepository.findCurriculumByMemberId(memberId);
}

Unfortunately, upon restart of my boot application, the entities are still cached in Redis and I get a org.hibernate.LazyInitializationException

This might be for the reason described in this post i.e. access to a detached object by hibernate - in my case the serialized object left around in the cache.

Can someone please advise a strategy for dealing with this problem?

  1. Should I clean/empty the cache upon destroy of my app bearing in mind the process of repopulating the cache is expensive and the app is going to be hosted in the cloud (Heroku) where the dynos/containers are destroyed and recreated (and therefore restarted) quite frequently.
  2. Or is there a way to reattach to the cached entities to the entity manager?
  3. Is there a better solution?

回答1:


Never used Redis, but if your cache is supposed to be persistent across application restarts you might want to fetch all needed relations before caching the entity. One other concern could be that those cached entities are detached, which can be a problem if you want to use them again in transactions. Of course, you might reattach them by calling merge(entity), which on the other hand could cause problems with overriding new data with cached ones.

Another thing to consider with persistent cache is class versions, because if you change your classes between redeploys, deserialization will fail if cache is already populated with instances of previous class version.



来源:https://stackoverflow.com/questions/26531305/lazyinitializationexception-when-trying-to-access-detached-objects-left-around-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!