如何通过URL调用Spring Boot中PagingAndSortingRepository的findAllByStatusIn方法
解决Spring Data REST中findAllByStatusIn的URL调用问题
我来帮你搞定这个问题!你尝试的{3,1}格式Spring Data REST默认并不识别,下面给你两种可行的调用方式:
方式一:重复参数名传递多个值
这是最直接且无需额外配置的方法,只需要多次使用同一个参数名来传递不同状态值:
http://localhost:8080/foobar/search/findAllByStatusIn?stati=3&stati=1
Spring Data REST会自动把这些重复的stati参数值收集成Collection<Integer>,传递给你的findAllByStatusIn方法。
方式二:逗号分隔的单个参数值(需额外配置)
如果你更倾向于用单个参数传递多个值,需要添加自定义转换器让Spring能将逗号分隔的字符串解析为整数集合。
创建一个配置类:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.converter.Converter; import java.util.Arrays; import java.util.Collection; import java.util.stream.Collectors; @Configuration public class RestConfig { @Bean public Converter<String, Collection<Integer>> stringToIntegerCollectionConverter() { return source -> Arrays.stream(source.split(",")) .map(Integer::parseInt) .collect(Collectors.toList()); } }
配置完成后,就可以用下面的URL调用了:
http://localhost:8080/foobar/search/findAllByStatusIn?stati=3,1
额外检查点
- 先访问
http://localhost:8080/foobar/search,确认findAllByStatusIn方法是否出现在可用查询列表中,这能确保你的仓库接口已经被Spring Data REST正确暴露。 - 确认你的
@Param("stati")注解参数名和URL中的查询参数名完全一致(大小写敏感)。
内容的提问来源于stack exchange,提问作者Martin
相关产品推荐
相关产品推荐

