我正在使用spring数据(spring boot)和mongodb。我有这两个 实体
@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 );
然后我遇到此错误:
“无法创建对具有NULL id的对象的引用。 导致org.springframework.data.mapping.model.MappingException:无法 创建对具有NULL id mongo hibernate的对象的引用。”
任何人都可以解释我们如何使用设备实体存储用户实体。如果我先保存设备实体并设置为用户实体,则可以正常工作,但我只想保存用户实体,它将自动保存设备实体。
答案 0 :(得分:0)
发生这种情况是因为hibernate尚未获得ID,因为它尚未创建,因此您需要先将Device保存到DB,然后将其设置为用户实体。
类似下面的内容。
B b = new B();
mongoOperations.save(b);
A a = new A();
a.setB(b)
mongoOperations.save(a);
答案 1 :(得分:0)
映射框架不处理级联保存。如果更改了Person对象引用的Account对象,则必须单独保存Account对象。在Person对象上调用save不会自动将Account对象保存在accounts属性中。
请阅读以下文档;