Reputation: 5749
I try without success to save a many to many relation.
In my lodger class
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, mappedBy = "lodger")
private List<Contact> contactList;
In my contact class
@ManyToMany
@JoinTable(name = "lodger_contact", joinColumns = @JoinColumn(name = "contact_id"), inverseJoinColumns = @JoinColumn(name = "lodger_id"))
private List<Lodger> lodger;
How i save the relation
public void associateDissociateLodgerAndContact(Long lodgerId, List<Long> contactIdToDissociates, List<Long> contactIdToAssociates) {
Lodger lodger = lodgerRepository.findOne(lodgerId);
List<Contact> contactList;
if (lodger.getContactList() == null) {
lodger.setContactList(new ArrayList<>());
contactList = lodger.getContactList();
} else {
contactList = lodger.getContactList();
}
if (contactIdToDissociates != null) {
for (Iterator<Contact> iterator = contactList.iterator(); iterator.hasNext();) {
Contact contact = iterator.next();
for (Long contactId : contactIdToDissociates) {
if (contact.getContactId().longValue() == contactId.longValue()) {
iterator.remove();
break;
}
}
}
}
List<Contact> contactToAssign = contactRepository.findAll(contactIdToAssociates);
lodger.getContactList().addAll(contactToAssign);
lodgerRepository.save(lodger);
}
Before I do the save, I try to add 2 contact to lodger and remove one. Just before the save, i see there are 2 element in getContactList.
When I do the save, no query is done.
Upvotes: 0
Views: 46
Reputation: 4154
Since this is bi-directional relationship, you should link/unlink both sides of the relationship. You are only updating the relationship from one side - from the Lodger
side.
Upvotes: 1