简体   繁体   English

Spring Data Mongo - 如何通过@DBRef字段的id进行查询

[英]Spring Data Mongo - How to query by @DBRef field's id

I am new to Spring Data Mongo so I must be doing something wrong because I can't manage to execute such a simple query. 我是Spring Data Mongo的新手,所以我一定做错了,因为我无法设法执行这么简单的查询。 This is my model: 这是我的模特:

@Document(collection="brands")
public class Brand{
    @Id
    private int id;

    private String name;
    ...
    //getters-setters
}

@Document(collection="models")
public class Model{
    @Id
    private int id;
    private String name;
    @DBRef
    private Brand brand;
    ...
    //getters-setters
}

I would like to get all models from a brand, so I implement the DAO as follows: 我想从一个品牌获得所有模型,所以我实现DAO如下:

@Repository
public interface IModelDAO extends MongoRepository<Model, Integer>{
    @Query(value="{ 'brand.$id' : ?0 }")
    public List<Model> findByBrandId(Integer id);   
}

If I execute this mongodb query in the shell it works: db.modelss.find({ 'brand.$id' : 1 }) 如果我在shell中执行这个mongodb查询它可以工作: db.modelss.find({ 'brand.$id' : 1 })

But, the Java application throws the following exception: 但是,Java应用程序抛出以下异常:

Caused by: java.lang.IllegalAccessError
at org.springframework.data.mapping.PropertyReferenceException.detectPotentialMatches(PropertyReferenceException.java:134)

Apparently it is looking for a field $id in Brand class, and since it doesn't exist it fails. 显然它正在寻找Brand类中的字段$ id,因为它不存在,所以它失败了。 So I change the query to the following, so that it navigates to the id field: 所以我将查询更改为以下内容,以便导航到id字段:

@Query(value="{ 'brand.id' : ?0 }")

Now, it doesn't throw an exception but it doesn't find anything in the DB. 现在,它不会抛出异常,但它在DB中找不到任何内容。

Debugging the MongoTemplate.executeFindMultiInternal() method in can see that in 调试MongoTemplate.executeFindMultiInternal()方法可以看到它

DBCursor cursor = null;
    try {
        cursor = collectionCallback.doInCollection(getAndPrepareCollection(getDb(), collectionName));

cursor's query is query={ "brand" : 134} . cursor的查询是query={ "brand" : 134} So it makes sense it doesn't find anything. 所以它没有找到任何东西是有道理的。 Changing the query value during debugging to query={ "brand.$id" : 134} it works. 在调试期间将查询值更改为query = {“brand。$ id”:134}它可以正常工作。

So, why isn't the query correctly translated? 那么,为什么查询没有正确翻译?

The problem was caused by the @Id int type. 问题是由@Id int类型引起的。 Changing it to Integer solved it: 将其更改为整数解决了它:

@Document(collection="brands")
public class Brand{
    @Id
    private Integer id;

    private String name;
    ...
    //getters-setters
}

@Document(collection="models")
public class Model{
    @Id
    private Integer id;
    private String name;
    @DBRef
    private Brand brand;
    ...
    //getters-setters
}

try this; 试试这个;

Query que = new Query();
que.addCriteria(Criteria.where("user.$id").is(new ObjectId("123456789012345678901234")));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM