首页 > 解决方案 > 无法创建对具有 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 的对象的引用。”

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

标签: mongodbspring-boot

解决方案


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

像下面的东西。

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

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

推荐阅读