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.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With