Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create a reference to an object with a NULL id mongo hibernate-mongo and spring boot

I am using spring data(spring boot ) and mongodb . I have these two entities

@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("[email protected]");
 user.setDevice( device );
 userRepo.save( user );

Then i have got this error :

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

Can anyone explain how to we store userentity with deviceentity. If i save device entity first and set to user entity i works fine but i want to save only user entity and it will save device entity automatically.

like image 565
Anuj Dhiman Avatar asked Aug 21 '18 07:08

Anuj Dhiman


2 Answers

This is happening becuase hibernate is not able to get id as it is not yet created so you need to save Device to DB first then set it into user entity.

Something like below.

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

A a = new A();
a.setB(b)
mongoOperations.save(a);
like image 127
Alien Avatar answered Oct 15 '22 23:10

Alien


The mapping framework does not handle cascading saves. If you change an Account object that is referenced by a Person object, you must save the Account object separately. Calling save on the Person object does not automatically save the Account objects in the accounts property.

Read below document please;

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

like image 22
yusuf Avatar answered Oct 15 '22 23:10

yusuf