1

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?
  }

1 Answer 1

2

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.

7
  • Will you please elaborate?
    – imbond
    Jun 21, 2015 at 11:52
  • I don't know what to add. What don't you understand?
    – JB Nizet
    Jun 21, 2015 at 11:53
  • "Calling entityManager.persist(user) is sufficient,"... What do I need to change in above mentioned controller? Shall I add user and address details as an input json for the created API?
    – imbond
    Jun 21, 2015 at 11:55
  • You need to make the method compile by returning a Status. Your method already takes a user as argument, and inside the user, you have the user's address. So the method passes the user (containing his address) to the service, which, I guess, passes it to the DAO, which just needs to persist the user. Persisting the user will also persist the user's address.
    – JB Nizet
    Jun 21, 2015 at 11:59
  • I did the same, but when I passing the JSON as an input using address parameters then it prompts 404 and when I remove address parameters and kept just user parameter then it prompts that "Column 'AddressId' cannot be null"
    – imbond
    Jun 21, 2015 at 12:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.