Spring Data Mongo - 如何通过@DBRef字段的id进行查询 [英] Spring Data Mongo - How to query by @DBRef field's id

查看:1541
本文介绍了Spring Data Mongo - 如何通过@DBRef字段的id进行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring Data Mongo的新手,所以我必须做错事,因为我无法设法执行这么简单的查询。这是我的模特:

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. 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
}

我想从一个品牌获得所有模型,所以我按如下方式实现DAO:

I would like to get all models from a brand, so I implement the DAO as follows:

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

如果我在shell中执行这个mongodb查询它可以工作: db.modelss.find({'brand。$ id':1})

If I execute this mongodb query in the shell it works: db.modelss.find({ 'brand.$id' : 1 })

但是,Java应用程序抛出以下异常:

But, the Java application throws the following exception:

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

显然它正在寻找Brand类中的字段$ id,因为它不存在它失败了。所以我将查询更改为以下内容,以便导航到id字段:

Apparently it is looking for a field $id in Brand class, and since it doesn't exist it fails. So I change the query to the following, so that it navigates to the id field:

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

现在,它不会抛出异常,但它在DB中找不到任何内容。

Now, it doesn't throw an exception but it doesn't find anything in the DB.

调试MongoTemplate.executeFindMultiInternal()方法可以看到

Debugging the MongoTemplate.executeFindMultiInternal() method in can see that in

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

光标的查询是 query = {brand:134} 。所以它没有找到任何东西是有道理的。在调试期间将查询值更改为query = {brand。$ id:134}它可以正常工作。

cursor's query is 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.

那么,为什么查询没有正确翻译?

So, why isn't the query correctly translated?

推荐答案

问题是由 @Id int 类型。将其更改为整数解决了它:

The problem was caused by the @Id int type. 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
}

这篇关于Spring Data Mongo - 如何通过@DBRef字段的id进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆