Salut
J'ai une relation many to many.
Dans ma classe lodger
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3 @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, mappedBy = "lodger") private List<Contact> contactList;
Dans ma classe contact
Dans la bd, j'ai des données dans chacune de ses tables, je voudrais maintenant faire des associations entre les deux.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4 @ManyToMany @JoinTable(name = "lodger_contact", joinColumns = @JoinColumn(name = "contact_id"), inverseJoinColumns = @JoinColumn(name = "lodger_id")) private List<Lodger> lodger;
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 public void associateDissociateLodgerAndContact(Long lodgerId, List<Long> contactIdToDissociates, List<Long> contactIdToAssociates) { Lodger lodger = lodgerRepository.findOne(lodgerId); List<Contact> contactList; // = contactRepository.findAll(contactIdList); 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); }
Aucune sauvegarde n'est fait.
Une idée?
Partager