首页 文章

Spring Cache - ClassCastException(ehcache)

提问于
浏览
0

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

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

    看起来名为“category”的缓存配置为保存Category元素:

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

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

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

    我想你想要你的缓存存储 List<Category> ;因此,当您尝试预热缓存时,应该放置 List<Category> 而不是放置类别 .

  • 0

    您要实现的目标不适用于Spring缓存抽象 . 您必须手动完成更多工作才能获得所需的结果 .

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

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

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

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

相关问题