如何使用存储库接口在Spring Data中通过其嵌套对象的objectId查找集合? [英] How to find collections by its nested object's objectId in Spring Data using repository interface?

查看:222
本文介绍了如何使用存储库接口在Spring Data中通过其嵌套对象的objectId查找集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoDB中有一个集合,其中包含这样的项目:

I have a collection in MongoDB that has items like this one:

{
    "_id" : ObjectId("53e4d31d1f6b66e5163962e3c"),
    "name" : "bob",
    "nestedObject" : {
        "_id" : ObjectId("53f5a623cb5e4c1ed4f6ce67")
        //more fields...
    }
}

该项目的Java表示如下:

Java representation of this item looks following:

public class SomeObject {
    @Id
    private String id;
    private String name;
    private NestedObject nestedObject;

    //getters and setters
}

Repository接口的定义如下:

The Repository interface is defined like this:

public interface SomeObjectRepository extends MongoRepository<SomeObject, String> {
    public List<SomeObject> findByName(String name);
    public List<SomeObject> findByNestedObjectId(String id);
    //some other find functions
}

现在,findByName(String name)可以正常工作,但是findByNestedObjectId(String id)不返回任何内容.

Now, findByName(String name) is working as it should be, but findByNestedObjectId(String id) returns nothing.

问题:是否可以使用存储库界面通过其嵌套对象的属性来查找集合项?如果没有,建议使用什么方法来解决此问题?是否可以不重新实现整个存储库?

Question is: is it possible to find collection items by it's nested object's attribute using repository interface? If not, what is the recommended way to approach this problem? Is it possible without reimplementing whole repository?

推荐答案

Spring-data-mongodb不会在查询操作时自动将嵌套类中的 _id 字段转换为 ObjectId 类型.您应该手动将其转换.例如:

Spring-data-mongodb would not convert _id field to ObjectId type automatically in nested class on query operation. You should convert it manually. For example:

public List<SomeObject> findByNestedObjectId(String id) {
    Query query = Query.query(new Criteria("nestedObject._id", convertToObjectId(id)));
    return mongoTemplate.find(query, SomeObject.class);
}

Object convertToObjectId(Object id) {
    if (id instanceof String && ObjectId.isValid(id)) {
        return new ObjectId(id);
    }
    return id;
}

这篇关于如何使用存储库接口在Spring Data中通过其嵌套对象的objectId查找集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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