imbond
imbond

Reputation: 2098

How to save two classes having one to one relationship using Hibernate?

I've created a Spring application using Hibernate in which I've implemented 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 an address class along with its getters and setters.
  2. Created a user class along with its getters and setters + @OneToOne mapping with address class.Like,
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "AddressId")
private Address address;
  1. Createed a DAO & Service class for user and address.
  2. 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 the 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?
  }

Upvotes: 1

Views: 235

Answers (1)

JB Nizet
JB Nizet

Reputation: 691695

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.

Upvotes: 2

Related Questions