Spring 数据Mongo - 如何通过@DBRef 字段的id 查询

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

我是 Spring 数据 Mongo 的新手,所以我一定是做错了什么,因为我无法执行这么简单的查询。这是我的模型:

@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 如下:

@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 })

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

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

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

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

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

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

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

游标的查询是query={ "brand" : 134}。所以它没有找到任何东西是有道理的。在调试期间将查询值更改为 query={ "brand.$id" : 134} 它有效。

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

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

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

试试这个;

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