Spring Cache - ClassCastException(ehcache)

时间:2017-02-23 17:22:04

标签: java spring ehcache

当我尝试从缓存中获取数据列表时,我遇到了问题。

CategoryServiceImpl:

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
@Resource
private CategoryRepository categoryRepository;

@Override
@Caching(
        put = {
                @CachePut(value = "category", key = "'findByParrentId-' + #category.parentId + ',' + #category.user.userId"),
                @CachePut(value = "category", key = "'findAll-' + #category.user.userId")
        }
)
public Category add(Category category) {
    return categoryRepository.saveAndFlush(category);
}

@Override
@Cacheable(cacheNames = "category", key = "'findByParrentId-' + #prntId + ',' + #userId")
public List<Category> findByParentId(long prntId, long userId) {
    return categoryRepository.findByParentId(prntId, userId);
}

@Override
@Cacheable(cacheNames = "category", key = "'findAll-' + #userId")
public List<Category> findAll(long userId) {
    return categoryRepository.findAll(userId);
}
}

当我尝试获取类别列表时:

List<Category> categories = new ArrayList<>(categoryService.findByParentId(parentId, userSession.getUser().getUserId()));

我得到一个例外:

  

ClassCastException:ru.mrchebik.model.Category无法强制转换为java.util.List

完整堆栈跟踪:http://pastebin.com/35A14ZW9

2 个答案:

答案 0 :(得分:0)

似乎名为“category”的缓存配置为保存Category元素:

@CachePut(value = "category", key = "'findByParrentId-' + #category.parentId + ',' + #category.user.userId")

然后你希望这个缓存返回List:

@Cacheable(cacheNames = "category", key = "'findAll-' + #userId")

我认为您希望缓存存储List<Category>;因此,当您尝试预热缓存时,应该放置List<Category>而不是放置类别。

答案 1 :(得分:0)

您尝试实现的内容不适用于Spring缓存抽象。你必须手动做更多才能得到你想要的结果。

首先,现在有了Spring缓存的方法来表达需要将单个元素添加到缓存中的集合。所以你需要自己维护映射的内容。

使用当前声明,您不仅在缓存中有Category而不是List<Category>,而且每个键只有最后Category个。

我建议您自行删除@CachePut注释并在缓存中进行收集更新。

请注意,这需要是线程安全的,可能需要更多考虑。