Spring Mongo Repository根据customerId列表查询Customer对象
问题修复方案
错误分析
你的CustomerRepository存在两个核心问题:
- 继承
MongoRepository时泛型类型错误,应该指定实体类为Customer而非Task - 查询方法定义不符合Spring Data MongoDB规范,不能在方法中硬编码参数值,且需要用
In关键字实现“匹配列表中任意值”的查询逻辑
正确的Repository写法
public interface CustomerRepository extends MongoRepository<Customer, String> { List<Customer> findAllByCustomerIdIn(List<String> customerIds); }
使用示例
在业务代码中调用该方法,传入目标customerId列表即可:
// 注入CustomerRepository @Autowired private CustomerRepository customerRepository; // 查询指定customerId的用户 List<String> targetIds = List.of("customer1", "customer2", "customer4"); List<Customer> customers = customerRepository.findAllByCustomerIdIn(targetIds); // 返回结果会包含customer1和customer2对应的对象,customer4不存在则不会返回
补充说明
- Spring Data MongoDB会自动将
findAllByCustomerIdIn解析为MongoDB的$in查询,匹配customerId字段在传入列表中的文档 - 实体类
Customer中缺少surname字段,如果需要映射存储数据中的该字段,需要补充属性:
public class Customer { @Id private String id; private String name; private String customerId; private String surname; // 添加该字段以映射存储数据中的surname }
内容的提问来源于stack exchange,提问作者sree
相关产品推荐
相关产品推荐

