【发布时间】:2020-05-08 01:38:32
【问题描述】:
我有以下问题-如何使用@Query通过嵌套属性查询?
我的产品类(Mongo 中的文档):
@Document(collection = "products")
public class Product {
@Id
private String id;
@DBRef
private ProductProperties properties;
它在 Mongo 中的样子:
{
"_id" : ObjectId("5d5e78d20e8e3d0006079a84"),
"companyId" : "1234",
"properties" : {
"$ref" : "properties",
"$id" : ObjectId("5df8dd2331ea7b4a9384335b")
},
"calendar" : [
{
"startDate" : ISODate("2019-09-04T22:00:00.000Z"),
"endDate" : ISODate("2019-09-09T22:00:00.000Z")
}
],
"_class" : "org.abc.def"
}
ProductProperties 类(Mongo 中的文档):
@Document(collection = "product_properties")
public class ProductProperties {
@Id
private String id;
(...)
它在 Mongo 中的样子:
{
"_id" : ObjectId("5df8dd2331ea7b4a9384335b"),
"brand" : "offer Brand_1",
"model" : "offer model_1",
"modelNumber" : "offer model number_1",
"size" : {
...
}
我的 Spring 存储库:
public interface ProductRepository extends MongoRepository<Product, String> {
@Query("{'properties.id': ?0 }")
List<Product> findByPropertiesId(String propertiesId);
我也试过了:
List<Product> findByProperties_id(String propertiesId)
或
@Query("{'properties.$id': ?0 }")
List<Product> findByPropertiesId(ObjectId propertiesId);
但没有成功。你知道怎么回事吗?
当我调用时:
public List<Product> findProductsByPropertiesId(String properties) {
if (properties == null) {
throw new IllegalArgumentException("onFind: propertiesId should not be null.");
}
return productRepository.findByProperties_Id(properties);
}
我得到空列表:(
也许通过 Query 不可能做到这一点?
【问题讨论】:
-
不幸的是我仍然没有解决我的问题。我想我尝试了所有选项......没有成功:(
-
这些不适用于您的情况。您在
Product类中使用 @DBRef 注释。请参阅这篇关于使用@DBRef的帖子:Spring Mongo DB @DBREF。什么是数据库引用?请参阅 MongoDB 文档中的 DBRefs。 -
还是不行。我在 JSON 中添加了 "properties" : { "$ref" : "properties", "$id" : ObjectId("5df8dd2331ea7b4a9384335b") }。我的存储库看起来像 @Query(value = "{'properties.id': ?0 }") List
findByPropertiesId(String propertiesId); -
我不知道是什么问题。 StackOverflow 和其他网站上都有很多相关的帖子。请尝试搜索“Spring MongoDB @DBRef”。仅作为建议:解决问题的一种方法是尝试在您自己和上运行一个示例,这样您就可以从工作代码开始并进一步将其应用于您的情况。
标签: mongodb spring-boot mongorepository