mongodb - 无法创建对具有 NULL id 的对象的引用 mongo hibernate-mongo 和 spring boot

标签 mongodb 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 );

然后我得到了这个错误:

"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."

谁能解释一下我们如何使用设备实体存储用户实体。如果我先保存设备实体并设置为用户实体,我工作正常,但我只想保存用户实体,它会自动保存设备实体。

最佳答案

发生这种情况是因为 hibernate 无法获取 ID,因为它尚未创建,因此您需要先将设备保存到数据库,然后将其设置到用户实体中。

类似下面的内容。

B b = new B();
mongoOperations.save(b);

A a = new A();
a.setB(b)
mongoOperations.save(a);

关于mongodb - 无法创建对具有 NULL id 的对象的引用 mongo hibernate-mongo 和 spring boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51943411/

相关文章:

Angular2 Ng2文件上传CORS问题

mongodb - 使用 nodejs 将非常大的记录集导入 MongoDB

javascript - 无法使用 Node js 将错误放入 REST API 中

java - 如何编写更新嵌入文档的查询

java - 无法在特定端点使用 thymeleaf 访问静态资源

java - 如何减少 TcpOutboundGateway 的超时?

node.js - 如何为部署到 Heroku 的 Node +mongo 应用程序播种数据?

mongodb - 基于对象数组的 MongoDB 过滤器

c# - 如何在 MongoDB 中为不同的字段名称注册 ScalarDiscriminatorConvention?

java - 在 WildFly 上部署 Spring Boot WAR