Java Spring缓存——ClassCastException(ehcache)
当我试图从缓存中获取数据列表时,我遇到了一个问题 CategoryServiceImpl:Java Spring缓存——ClassCastException(ehcache),java,spring,ehcache,Java,Spring,Ehcache,当我试图从缓存中获取数据列表时,我遇到了一个问题 CategoryServiceImpl: @Service @Transactional public class CategoryServiceImpl implements CategoryService { @Resource private CategoryRepository categoryRepository; @Override @Caching( put = { @CachePu
@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);
}
}
@服务
@交易的
公共类CategoryServiceImpl实现CategoryService{
@资源
私人分类报告分类报告;
@凌驾
@缓存(
put={
@CachePut(value=“category”,key=“'findByParrentId-'+#category.parentId+”,“+#category.user.userId”),
@CachePut(value=“category”,key=“'findAll-”+#category.user.userId”)
}
)
公共类别添加(类别){
返回类别repository.saveAndFlush(类别);
}
@凌驾
@可缓存(cacheNames=“category”,key=“'findByParrentId-”+#prntId+”,“+#userId”)
公共列表findByParentId(长prntId,长userId){
return categoryRepository.findByParentId(prntId,userId);
}
@凌驾
@可缓存(cacheNames=“category”,key=“'findAll-'+#userId”)
公共列表findAll(长用户ID){
返回categoryRepository.findAll(userId);
}
}
当我尝试获取类别列表时:
List<Category> categories = new ArrayList<>(categoryService.findByParentId(parentId, userSession.getUser().getUserId()));
List categories=new ArrayList(categoryService.findByParentId(parentId,userSession.getUser().getUserId());
我得到一个例外:
ClassCastException:ru.mrchebik.model.Category不能转换为java.util.List
完整堆栈跟踪:名为“category”的缓存似乎配置为保存category元素:
@CachePut(value = "category", key = "'findByParrentId-' + #category.parentId + ',' + #category.user.userId")
然后您希望这个缓存返回列表:
@Cacheable(cacheNames = "category", key = "'findAll-' + #userId")
我想您希望缓存存储
列表
;因此,当您尝试预热缓存时,您应该放置列表,而不是放置类别。您试图实现的目标与Spring缓存抽象不起作用。为了得到你想要的结果,你必须手工做更多的工作
首先,现在有一种使用Spring缓存的方法来表示需要将单个元素添加到缓存中的集合中。因此,您需要自己维护映射的内容
使用当前声明,不仅缓存中有一个类别
,而不是列表
,而且每个键只有最后一个类别
我建议删除@CachePut
注释,自己在缓存中更新集合
请注意,这需要线程安全,这可能需要更多的考虑。它可以工作,但我只给出一个元素。如果我想给出所有元素,我必须做什么?现在,我有了这个:public List add(Category Category){categoryRepository.saveAndFlush(Category);List List=new ArrayList();List.add(Category);return List;}
我可以创建List的局部变量,但这不是缓存。谢谢,我使用@cacheexecute
和allEntries
,我可以得到一个类别列表。