【问题标题】:Cannot create a reference to an object with a NULL id mongo hibernate-mongo and spring boot无法创建对具有 NULL id mongo hibernate-mongo 和 spring boot 的对象的引用
【发布时间】:2019-01-27 07:56:44
【问题描述】:

我正在使用 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 的对象的引用。] 与 root 导致 org.springframework.data.mapping.model.MappingException: 不能 创建对具有 NULL id mongo hibernate 的对象的引用。”

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

【问题讨论】:

    标签: mongodb spring-boot


    【解决方案1】:

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

    如下所示。

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

    【讨论】:

    • 是否无法保存用户实体和设备实体应该自动保存
    【解决方案2】:

    映射框架不处理级联保存。如果更改由 Person 对象引用的 Account 对象,则必须单独保存 Account 对象。对 Person 对象调用 save 不会自动将 Account 对象保存在 accounts 属性中。

    请阅读以下文件;

    https://docs.spring.io/spring-data/mongodb/docs/2.1.4.RELEASE/reference/html/#mapping-usage-references

    【讨论】:

      猜你喜欢
      • 2021-09-17
      • 2016-10-02
      • 2019-03-14
      • 2018-12-18
      • 2019-03-31
      • 1970-01-01
      • 2018-12-06
      • 2014-03-09
      • 1970-01-01
      相关资源
      最近更新 更多