imbond imbond - 3 months ago 20
Java Question

How Hibernate - O/R Mappings using Spring - REST API will work?

I've created one to one relationship between user and address table. Two tables are created for the same like, one for the user and another for the address. Now, I would like to implement the same but facing hurdles. Following is my approach,

[1] Created address class along with its getters and setters
[2] Created user class along with its getters and setters + @OneToOne mapping with address class.
Like,

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "AddressId")
private Address address;


[3] Create DAO & Service class for user and address
[4] How do I call service class in my controller so that It took user and address details as my input and save the same in database?

@RequestMapping(value = "/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Status addUserAddress(@RequestBody User user)
throws Exception {
userServices.addUser(user);
// What shall I add here to save address also?
}

Answer

Calling entityManager.persist(user) is sufficient, since you have a cascade=ALL on the association: the entity manager will persist the user and cascade the persist operation on the address.