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

15

我刚接触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
}

我想获取某个品牌的所有型号,因此我按照以下方式实施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)

显然它正在Brand类中寻找一个名为 $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},就可以工作了。

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

2个回答

6
问题是由于 @Idint 类型引起的。将其更改为 Integer 可以解决问题:
@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
}

4

试试这个;

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

1
这在我的情况下不起作用。你能在这里给我指导吗?https://stackoverflow.com/questions/55401324/dbref-doesnt-pull-the-data-when-use-spring-data-mongo - PAA
我也遇到了同样的问题。我正在使用Spring Boot 2.1.6和spring-data-mongod 2.1.9。Spring似乎会将ObjectId转换为“$oid”,例如 {"user.$id":{"$oid":"123456789012345678901234"}} - Amnon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接