我无法通过ehcache获取数据列表。Spring Cache - 无法获取数据列表
的servlet上下文:
<cache:annotation-driven />
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cacheManager-ref="ehcache"/>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:configLocation="/WEB-INF/spring/appServlet/ehcache.xml" p:shared="true" />
ehcache.xml中
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="true" monitoring="autodetect" dynamicConfig="true">
<cache name="category"
maxEntriesLocalHeap="5000"
maxEntriesLocalDisk="1000"
eternal="false"
diskSpoolBufferSizeMB="20"
timeToIdleSeconds="200"
timeToLiveSeconds="500"
memoryStoreEvictionPolicy="LFU"
transactionalMode="off">
<persistence strategy="localTempSwap"/>
</cache>
我有类别的实体:
@Entity
@Table(name = "categories")
public class Category implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long categoryId;
@Column(nullable = false)
private String name;
private long level;
private long parentId;
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "categories")
private Set<Post> posts;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userId")
private User user;
public Category() {
}
public Category(User user, long level, String name, long parentId) {
this.user = user;
this.level = level;
this.name = name;
this.parentId = parentId;
}
// ...
}
然后,我尝试缓存此方法:
@Service
@Repository
@Transactional
public class CategoryServiceImpl implements CategoryService {
@Resource
private CategoryRepository categoryRepository;
@Override
@CachePut(value = "category", key = "#category.categoryId")
public Category add(Category category) {
return categoryRepository.saveAndFlush(category);
}
@Override
@Cacheable("category")
public Category findById(long id) {
return categoryRepository.findOne(id);
}
@Override
@Cacheable("category")
public Category findByParentIdThroughCategoryId(long prntId, long userId) {
return categoryRepository.findByParentIdThroughCategoryId(prntId, userId);
}
@Override
@Cacheable("category")
public List<Category> findByParentId(long prntId, long userId) {
return categoryRepository.findByParentId(prntId, userId);
}
@Override
@Cacheable("category")
public List<Category> findAll(long userId) {
return categoryRepository.findAll(userId);
}
@Override
@CacheEvict("category")
public void remove(long id) {
categoryRepository.delete(id);
}
}
当增加一个类别,然后尽量把它来查看有用户所有类别findByParentId /的findall,它返回一个空列表
[]
它这样做,例如我缓存的类别,然后采取类别的列表,我试图得到类别与ID 11 - findById,并发现:
请首先确认'categoryRepository.findAll(userId)'和'categoryRepository.findByParentId(prntId,userId)'在直接调用时会返回一些内容。另一个无关的评论是你的'CategoryServiceImpl'类不应该用'@ Repository'注释,只有你的'CategoryRepository'应该。 – artemisian
这个方法返回值。如果不成功,我不会进行缓存。 嗯...我总是这样做@Repository和所有作品。我把'@ Repository'移到'CategoryRepository',谢谢。 – shank
@artemisian我也尝试这样做:'@Cacheable(cacheNames =“category”,key =“#userId”)'但它没有任何改变 – mrchebik