dbref java_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!

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值