【问题标题】:@DBRef doesn't pull the Data when use Spring Data Mongo@DBRef 在使用 Spring Data Mongo 时不提取数据
【发布时间】:2019-03-28 15:25:04
【问题描述】:

我使用了来自Error creating bean with name 'personRepository': Invocation of init method failed; nested exception is com.mongodb.util.JSONParseException:的代码,现在尝试调用

Person p = personRepository.findByAddresses_City("London NW1");
System.out.println("PERSON FOR ADDRESS = "+p);

我得到空响应。

另外,下面的查询不会拉任何东西。

Query query = new Query(Criteria.where("address.$id").is(2L));
List<Person> l = mongoTemplate.find(query, Person.class);
System.out.println(l);

这里:

db.getCollection('address').find({})

/* 1 */
{
    "_id" : NumberLong(1),
    "address" : "221b Baker Street",
    "city" : "London NW1",
    "state" : "London",
    "zipcode" : NumberLong(12345),
    "_class" : "com.example.demo.model.Address"
}

db.getCollection('person').find({})

/* 1 */
{
    "_id" : NumberLong(1),
    "name" : "Achilles",
    "age" : 0,
    "addresses" : [],
    "_class" : "com.example.demo.model.Person"
}

/* 2 */
{
    "_id" : NumberLong(2),
    "name" : "Hektor",
    "age" : 0,
    "addresses" : [ 
        {
            "$ref" : "address",
            "$id" : NumberLong(1),
            "$db" : "address"
        }
    ],
    "_class" : "com.example.demo.model.Person"
}

如何解决这个错误?

@Document(collection = "address")
public class Address {

    @Id
    private long addressId;
    private String address;
    private String city;
    private String state;
    private long zipcode;

    public Address() {
        System.out.println("CAlling default cons");
    }

    @PersistenceConstructor
    public Address(long addressId, String address, String city, String state, long zipcode) {
        this.addressId = addressId;
        this.address = address;
        this.city = city;
        this.state = state;
        this.zipcode = zipcode;
    }
    // setter and getter... toString()..
}

@Document
public class Person {
    @Id
    private Long personId;

    private String name;

    private int age;

    @DBRef(db = "address")
    private List<Address> addresses = new ArrayList<>();

    public Person() {
    }

    @PersistenceConstructor
    public Person(Long personId, String name, int age) {
        super();
        this.personId = personId;
        this.name = name;
        this.age = age;
    }
    // setter, getter and toString
}

【问题讨论】:

    标签: spring mongodb spring-data-mongodb


    【解决方案1】:

    这按设计工作。 MongoDB 不允许通过查询进行应用程序级连接,您需要使用聚合框架进行更复杂的查询。因此,存储库查询仅允许通过完整值(即 Address 对象)或标识符来查找 DBRef。

    如果您将 where 子句修复为 address.addressId,第二个示例应该可以工作。

    P.S.:请避免仅仅因为您在这里没有立即得到答案而提交票证。如果您提交工单,请务必附上带有测试用例的示例项目。

    【讨论】:

    • 我了解到,如果我使用 ObjectId 数据类型来存储 _id 值,那么存储库查询都不起作用。为什么?如果我使用 String 作为 _id 那么它工作正常。你能解释一下吗?
    猜你喜欢
    • 2017-07-18
    • 1970-01-01
    • 2017-10-30
    • 2021-09-24
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    相关资源
    最近更新 更多