无法创建对具有NULL id mongo hibernate-mongo和spring boot的对象的引用 [英] Cannot create a reference to an object with a NULL id mongo hibernate-mongo and spring boot
问题描述
我正在使用spring数据(spring boot)和mongodb.我有这两个 实体
I am using spring data(spring boot ) and mongodb . I have these two entities
@Document(collection = "users")
public class UserEntity {
private String email;
@DBRef
private DeviceEntity device;
}
@Document(collection = "device")
public class DeviceEntity {
private String name;
}
and I am creating the first object of device then setting it to user
entity. Now i will save user entity.
DeviceEntity Device = new DeviceEntity();
device.setName("demo");
UserEntity user = new UserEntity();
user.setEmail("demo@gmail.com");
user.setDevice( device );
userRepo.save( user );
然后我遇到了这个错误:
Then i have got this error :
无法创建对具有NULL id的对象的引用.] 导致org.springframework.data.mapping.model.MappingException:无法 创建对具有NULL id mongo hibernate的对象的引用."
"Cannot create a reference to an object with a NULL id.] with root cause org.springframework.data.mapping.model.MappingException: Cannot create a reference to an object with a NULL id mongo hibernate."
任何人都可以解释我们如何使用设备实体存储用户实体.如果我先保存设备实体并设置为用户实体,则可以正常工作,但我只想保存用户实体,它将自动保存设备实体.
Can anyone explain how to we store userentity with deviceentity. If i save device entity first and set to user entity i works fine but i want to save only user entity and it will save device entity automatically.
推荐答案
发生这种情况是因为hibernate无法获取ID(因为尚未创建ID),因此您需要先将Device保存到DB,然后将其设置为用户实体.
This is happening becuase hibernate is not able to get id as it is not yet created so you need to save Device to DB first then set it into user entity.
如下所示.
B b = new B();
mongoOperations.save(b);
A a = new A();
a.setB(b)
mongoOperations.save(a);
这篇关于无法创建对具有NULL id mongo hibernate-mongo和spring boot的对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!