awesome
awesome

Reputation: 317

How to save an object with null dbref in mongodb java spring?

I'm looking for a solution to save an object with a null dbref in mongodb java spring framework. Consider the following example:

@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;
}

Now if I instantiate A, i.e. A a = new A(); and save this object to mongodb via repository, i.e. aRepo.save(a). Then, I have the following exception:

org.springframework.data.mapping.model.MappingException: Cannot create a reference to an object with a NULL id.

Is there a way to save an object with a null dbref?

Thanks for your help!

Upvotes: 12

Views: 12039

Answers (4)

Ben
Ben

Reputation: 4279

Dbref encapsultes multi collection data fetching in a FOREGIN KEY kinda-way. If you're using @DBRef on a field it means that you have this entity already stored, so it must have an @Id. If you want to just store data in an object without cross-collection reference just remove the @DBRef annotation.

For example this is how your data looks in mongodb with @DBRef:

{
    "_id" : ObjectId("5bd1e18ee5adfb64cf7edc5c"),
    "b" : {
        "$ref" : "b",
        "$id" : ObjectId("5bd1e1b7e5adfb65f847159d")
    },
    "_class" : "namespace.A"
}

And this is how it looks without @DBRef

{
    "_id" : ObjectId("5bd1e18ee5adfb64cf7edc5c"),
    "b" : {
        "id" : "someid",
        "anotherfield" : "somevalue"
    },
    "_class" : "namespace.A"
}

Here's how to set a dbref field:

B b = bRepository.findById("someid").get();
A a = new A();
a.setB(b);
aRepository.save(a);

Upvotes: 1

Charan
Charan

Reputation: 1

the only solution is that to remove @DBref annotation because @DBRef is an annotation that indicates the annotated field is to be stored using a DBRef.

docs: spring.io - DBRef

Upvotes: 0

VK321
VK321

Reputation: 5953

You are using @DBREF, so you need to create object B first to DB. You can do so:

B b = new B();
mongoOperations.save(b);

A a = new A();
a.setB(b)
mongoOperations.save(a);

Upvotes: 1

bald2b
bald2b

Reputation: 189

As variant you can create NullObject like:

public final static B NULL_B = new B("");

and use it instead of null

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

Upvotes: -1

Related Questions