mongodb - 无法创建对具有 NULL id mongo hibernate-mongo 和 spring boot 的对象的引用
问题描述
我正在使用 spring data(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 的对象的引用。”
谁能解释我们如何用设备实体存储用户实体。如果我先保存设备实体并设置为用户实体,我可以正常工作,但我只想保存用户实体,它会自动保存设备实体。
解决方案
发生这种情况是因为休眠无法获取 id,因为它尚未创建,因此您需要先将设备保存到数据库,然后将其设置为用户实体。
像下面的东西。
B b = new B();
mongoOperations.save(b);
A a = new A();
a.setB(b)
mongoOperations.save(a);
推荐阅读
- c# - 在 c# 和 mysql 中更新 qty datagrid
- javascript - 使用 socket.io 的通知系统
- ios - UITableViewCell 忽略自动布局
- asp.net-mvc - MVC Core 中的模型绑定空值
- postgresql - Postgres - 删除操作未完成
- javascript - 在滚动条中设置背景透明不会显示其下方的文本
- f# - 函数参数中的通用模式匹配
- python - 零的滚动平均值未按预期返回零
- python - 编写 python 函数,使用 groupby 对每种索引类型的某些行的值求和
- laravel - Laravel 会话 ID 在每个请求上都会更改