如何在mongodb java spring中保存null dbref的对象?

awe*_*ome 10 java spring mongodb spring-data spring-data-mongodb

我正在寻找一种解决方案,在mongodb java spring框架中使用null dbref保存对象.请考虑以下示例:

@Document
public class A {
    @Id
    private String id;
    @DBRef
    private B b;

    public A() {
        this.b = null;
    }

    ...
}

@Document
public class B {
    @Id
    private String id;
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我实例化A,即A a = new A();通过存储库将此对象保存到mongodb,即aRepo.save(a).然后,我有以下例外:

org.springframework.data.mapping.model.MappingException: Cannot create a reference to an object with a NULL id.
Run Code Online (Sandbox Code Playgroud)

有没有办法用null dbref保存对象?

谢谢你的帮助!

bal*_*d2b -1

作为变体,您可以创建 NullObject,例如:

public final static B NULL_B = new B("");
Run Code Online (Sandbox Code Playgroud)

并使用它代替 null

public A() {
    this.b = NULL_B;
}
Run Code Online (Sandbox Code Playgroud)