Spring data 带MongoDB的Spring数据-按可空字段查找
我有一个Mongo收藏,其中包含以下文档:Spring data 带MongoDB的Spring数据-按可空字段查找,spring-data,spring-data-mongodb,spring-mongodb,mongotemplate,Spring Data,Spring Data Mongodb,Spring Mongodb,Mongotemplate,我有一个Mongo收藏,其中包含以下文档: a: { product: 1, country: 2, stock: 1} b: { product: 1, country: 3, stock: 3} c: { product: 2, country: 1, stock: 1} findByProductAndCountry(1, 2) //returns document a findByProductAndCountry(1, null) //returns documents a and
a: { product: 1, country: 2, stock: 1}
b: { product: 1, country: 3, stock: 3}
c: { product: 2, country: 1, stock: 1}
findByProductAndCountry(1, 2) //returns document a
findByProductAndCountry(1, null) //returns documents a and b
有时我想得到所有国家/地区的产品库存,所以我检索所有国家/地区的产品库存,然后添加它们,有时我想得到特定国家/地区的库存
是否可以采用以下单一方法:
findByProductAndCountry(Integer product, Integer country)
其工作原理如下:
a: { product: 1, country: 2, stock: 1}
b: { product: 1, country: 3, stock: 3}
c: { product: 2, country: 1, stock: 1}
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);
}
}
}
是的,当然我可以自己编写代码,但是我在寻找Spring数据中的原生数据。答案是不,不能对Spring数据进行这样的查询,因为它实际上是两个不同的查询。我建议将该方法放在定义其他查询方法的同一存储库中