Ho 2 entità: User e UsersList.Hibernate @ManyToMany delete relation
@Entity
@Table(name = "USERS")
public class User {
@Id
@GeneratedValue
@Column(name = "ID")
private Long id;
@ManyToMany(cascade = CascadeType.REMOVE, mappedBy = "users")
private List<UsersList> usersLists = new ArrayList<UsersList>();
public List<UsersList> getUsersLists() {
return usersLists;
}
public void setUsersLists(List<UsersList> usersLists) {
this.usersLists = usersLists;
}
}
e
@Entity
@Table(name = "USERS_LIST")
public class UsersList {
@Id
@GeneratedValue
@Column(name = "ID")
private Long id;
@ManyToMany
private List<User> users = new ArrayList<User>();
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
e codice come questo:
// 1
List<User> dbUsers; // 3 the user instances are persisted in DB
UsersList usersList = new UsersList();
usersList.setUsers(dbUsers);
// 2 - now persist the usersList using hibernate...
saveWithHibernate(usersList);
//3 - delete using a persisted user
deleteWithHibernate(dbUsers.get(0).getId());
dove
deleteWithHibernate(Long id) {
User usr = hibernateTemplate.get(User.class, id);
hibernateTemplate.delete(usr);
}
Nel passaggio 1 ho 3 righe nel utenti (USER_ID) Tavolo .
Dopo il passaggio 2 (secondo commento) Ho 1 riga nella tabella USERS_LIST (USERS_LIST_ID) e nella tabella di join USERS_LIST_USERS (USER_ID, USERS_LIST_ID) 3 righe.
Quello che voglio ottenere nel passaggio 3 è il seguente: quando elimino un utente dalla tabella UTENTI - diciamo utente con USER_ID = 4, voglio solo la riga con USER_ID = 4 dalla tabella di join da eliminare e gli altri a rimanere.
C'è una soluzione di annotazione al mio problema?
Che aspetto ha il metodo deleteWithHibernate? –