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!
java
spring
mongodb
spring-data
spring-data-mongodb
|
this question
edited Oct 28 '14 at 8:11
Christoph Strobl 2,942 7 18 asked Oct 27 '14 at 15:41
awesome 77 2 16 Generally speaking the error you're referring to occurs whenever you try to save an Entity that points to a referenced (non
null) one that has not been saved yet or does not have an
id set. Given the code above I cannot reproduce the issue - so I'm curious which version of
spring-data-mongodb are you using? –
Christoph Strobl Oct 28 '14 at 7:45 Indeed, I checked the sources and there is a check like id == null? throw exception. My version is 1.6.0.RELEASE –
awesome Oct 29 '14 at 13:13 Hey! I have the same problem. Have you found any solution? –
gabby Nov 5 '14 at 21:43 unfortunately, the only solution I found is to get rid of the @dbref... –
awesome Jul 29 '15 at 17:48
|
1 Answers
1
As variant you can create NullObject like:ith bi-directional relationship with Spring Data & DBRef, it gets into end-less cycle and keeps reading the association again and again. The domain class looks like class Category{ private String name; private Category parentCategor
public final static B NULL_B = new B("");
and use it instead of null
public A() {
this.b = NULL_B;
}
|
this answer answered Apr 1 '15 at 15:12
bald2b 111 2 And spring-data add only one empty document to B collection for all calling save() method with NullObject –
bald2b Apr 1 '15 at 15:16
|
ference to A and it is annotated with @DBRef. Class A: @Document(collection = "a")public class A {@Idpublic String id;/** The TicketGrantingTicket this is associated with. */@Fieldpublic String name;public A(String id, String name)