0

I need to upload addresses for a user. User has two addresses , address and postal address, if these addresses are different to each other it is easy I will save both addresses but how to keep the ids the same if the addresses are the same ?

User class

private Address address;
private Address postalAddress;
....

Code

 ....
 session.save(user.getAddress());
 session.save(user.getPostalAddress());
 .....

What to do if both addresses are the same?

J888
  • 1,944
  • 8
  • 42
  • 76

1 Answers1

2

You don't have to care about if these addresses are the same or not. Once you save an entity by using session.save(), that entity becomes managed. So the second save() won't do anything if the entity has already been saved.

EDIT:

Address addr = new Address();
user.setAddress(addr);
user.setPostalAddress(addr);

I am setting the same address to both address and postalAddress. Then if you do this:

session.save(user.getAddress());
session.save(user.getPostalAddress());

or do this (after defining cascade="persist" on the association):

session.save(user);

then Hibernate will insert only one row to address table and set the same id to user.address and user.postalAddress columns.

lunr
  • 5,159
  • 4
  • 31
  • 47
  • does that mean I should just use session.save(user) ? – J888 Jun 27 '13 at 02:57
  • That is different from the original question. You can do `session.save(user)`, but that won't save the addresses if you didn't define `cascade="persist"` on the association. – lunr Jun 27 '13 at 03:11
  • I am still on same question, I just do not get what you mean – J888 Jun 27 '13 at 03:19
  • The code in your original question will work, whether the `address` and `postalAddress` are the same or not. If you want to use just `session.save(user)`, you have to define a cascading persist operation. Take a look at here for an example: http://www.mkyong.com/hibernate/hibernate-cascade-example-save-update-delete-and-delete-orphan/ – lunr Jun 27 '13 at 03:27
  • It works but I do not what to save two different rows if addresses (address and postal ) are the SAME if they are the same need to save only one row and have a single foreign key in both address and postaladdress fileds in user table. – J888 Jun 27 '13 at 04:20
  • got you now please have a look at this question as well http://stackoverflow.com/questions/17080864/how-to-avoid-creating-a-new-row-if-similar-row-exists – J888 Jun 27 '13 at 05:05