相关疑难解决方法(0)

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

我是Spring Data 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
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Caused by: java.lang.IllegalAccessError
at org.springframework.data.mapping.PropertyReferenceException.detectPotentialMatches(PropertyReferenceException.java:134)
Run Code Online (Sandbox Code Playgroud)

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

@Query(value="{ 'brand.id' : ?0 }")
Run Code Online (Sandbox Code Playgroud)

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

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

DBCursor cursor = null;
    try { …
Run Code Online (Sandbox Code Playgroud)

java spring mongodb spring-data spring-data-mongodb

9
推荐指数
1
解决办法
2万
查看次数

标签 统计

java ×1

mongodb ×1

spring ×1

spring-data ×1

spring-data-mongodb ×1