我無法通過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