-
Notifications
You must be signed in to change notification settings - Fork 9
Bidirectional mapping
Kais OMRI edited this page Aug 20, 2018
·
2 revisions
Since the 2.2.0
version, RelMongo introduces the mappedBy property to enable bidirectional associations.
For example, when you have a Person document which references its cars documents, you can link a car to its owner and fetch it from the Car class. RelMongo will do the magic for you without changing the car document.
To use the OneToOne bidirectional mapping follow the following example:
// in person class
@OneToOne(fetch=FetchType.EAGER)
@JoinProperty(name = "passport")
private Passport passport;
//in passport class
@OneToOne(mappedBy = "passport", fetch = FetchType.EAGER)
private Person owner;
To use the OneToMany bidirectinal mapping follow the following example:
//in person class
@OneToMany(fetch=FetchType.EAGER, cascade = CascadeType.ALL)
@JoinProperty(name="carsrefs")
private List<Car> cars;
//in car class
@ManyToOne(mappedBy="cars")
private Person owner;
Now, when you find the car, RelMongo automatically loads the associated owner for you :
//create car and person and save them
...
person.setCars(Arrays.asList(new Car[] { savedCar }));
person = repository.save(person);
//retrieve the saved car
Car car = carRepository.findById(savedCar.getId().toString());
assertEquals(car.getOwner().getId(), person.getId());
© Copyright Kais OMRI under the Apache License 2.0