spring-data - Spring Data with MongoDB - 按可空字段查找
问题描述
我有一个 Mongo 集合,其中包含如下文件:
a: { product: 1, country: 2, stock: 1}
b: { product: 1, country: 3, stock: 3}
c: { product: 2, country: 1, stock: 1}
有时我想获取所有国家/地区的产品库存(因此我检索所有国家/地区的产品库存,然后添加它们),有时我想要特定国家/地区的库存。
是否可以制作一个单一的方法,如:
findByProductAndCountry(Integer product, Integer country)
像这样工作:
findByProductAndCountry(1, 2) //returns document a
findByProductAndCountry(1, null) //returns documents a and b
提前致谢!
解决方案
回答您的问题:不。不可能在 mongodb 中编写这样的查询,因此您无法使用单个 spring data mongodb 方法来实现。
我建议在存储库接口中为此编写一个默认方法。这样您就可以使用其他查询方法:
public interface ProductRepository extends MongoRepository<Product, String> {
List<Product> findByProduct(int product);
List<Product> findByProductAndCountry(int product, int country);
default List<Product> findByProductAndNullableCountry(Integer product, Integer country) {
if (country != null) {
return findByProductAndCountry(product, country);
} else {
return findByProduct(product);
}
}
}
推荐阅读
- kubernetes - 根据 Kubernetes Ingress 中的路径动态设置服务名称
- reactjs - 我如何让一个对象像孩子一样通过
- visual-studio - 在 Visual Studio 2019 中配置 Microsoft 身份平台时出错
- azure-pipelines - 我需要转义 SQL Deploy 数据库密码中的字符吗?如何?
- java - Discord4J 问题:改为循环发送消息
- libreoffice-calc - 相对参考未按预期工作的示例
- database - 在 Anylogic 中避免数据库查询
- android - Firebase Android:仅在多次刷新后才加载新数据
- drools - 累积/收集与单个 java 循环
- apache-spark - GLM Logit Link 与 Spark 中的族多项式