0

Using org.springframework.data.repository.CrudRepository, how can I add a many-to-many relationship to another exiting record with only the key reference to that entity.

For example:

If a person has a many to many relationship with addresses, how can I add to an existing person a relationship to an existing address by just using the address primary key.

Matt
  • 873
  • 1
  • 9
  • 24

1 Answers1

1

Make sure to define relationships at pojo level , and use findBy or findOne to find the address object with primary key of address and set the address in person and call save ,

Address address = addressrepo.findOne(addressprimarykey);

person.setAddress(address);

personrepo.save(person);
Srinivasan Sekar
  • 2,049
  • 13
  • 22
  • Wont this result in a database call to find the address and a database call to create the relationship? It this really necessary within this framework? – Matt May 05 '19 at 12:49
  • Yes , if you create address object with same primary key and details and then you try to save it , you will get constraint exception. Remember the states of the object transient , persistent and detached. – Srinivasan Sekar May 06 '19 at 04:19
  • So similar to other ORMs, I could attach an object with the primary key. Is there an API to attach an object without a hit to the database? – Matt May 06 '19 at 04:21
  • Lol. It can’t be done. Merge will call the database if the entity isn’t in the session cache, if I am not incorrect. – Matt May 06 '19 at 04:24
  • Yes you can't more on https://stackoverflow.com/questions/912659/what-is-the-proper-way-to-re-attach-detached-objects-in-hibernate – Srinivasan Sekar May 06 '19 at 04:33