我正在尝试使用Spring,如下代码所示。
@Repository
public interface EmployeeCrud extends CrudRepository<Employee, Integer> {
@Cacheable(cacheNames = "emp_by_last_name, key = "#lastName")
List<Employee> findAllByLastName(@Param("lastName") String lastName);
}由于接口没有参数名称(除非在启用调试信息的情况下编译),所以由于下面的异常,我无法获取数据。
java.lang.IllegalArgumentException: Null key returned for cache operation (maybe you are using named params on classes without debug info?) Builder[public abstract java.util.List EmployeeCrud.findAllByLastName(java.lang.String)] caches=[emp_by_last_name] | key='#lastName' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='' | unless='' | sync='false'
at org.springframework.cache.interceptor.CacheAspectSupport.generateKey(CacheAspectSupport.java:561)
at org.springframework.cache.interceptor.CacheAspectSupport.findCachedItem(CacheAspectSupport.java:502)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:389)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:327)
at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)即使我使用@Param或@P注释,CacheOperationExpressionEvaluator也无法解决它,因为它使用的是在内部使用StandardReflectionParameterNameDiscoverer和LocalVariableTableParameterNameDiscoverer的DefaultParameterNameDiscoverer。如果它也使用了AnnotationParameterNameDiscoverer,@Param就会被解析。
在不启用编译器、调试信息或实现EmployeeCrud接口的情况下,我们还需要哪些其他解决方案来使其工作呢?
发布于 2018-05-24 17:02:11
简单!如果未启用调试信息,则可以按位置引用参数,如.
@Cacheable(cacheNames = "emp_by_last_name, key = "#a0")
List<Employee> findAllByLastName(@Param("lastName") String lastName);有关更多细节,请参见参考文献。
另外,因为@Cacheable findAllByLastName(..)存储库方法只有一个参数,所以不需要显式调用键来将值存储在缓存("emp_by_last_name")中(在List<Employee>的情况下,方法返回值),因为在默认情况下,Spring的缓存抽象使用缓存方法的方法参数作为键。见这里。
您还应该注意这样一个事实,即缓存的结果(即键/值)将是整个Employee对象列表。如果您要查找的是列表中的元素,则不会单独缓存。如果您需要这种能力,那么请参考另一篇文章,我有一个以上的已应答。
希望这能有所帮助。
干杯!-John
https://stackoverflow.com/questions/50506552
复制相似问题