我有2個實體:User和UsersList。休眠@ManyToMany刪除關係
@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;
}
}
和
@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;
}
}
和這樣的代碼之一:
// 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());
其中
deleteWithHibernate(Long id) {
User usr = hibernateTemplate.get(User.class, id);
hibernateTemplate.delete(usr);
}
在步驟1我在USERS 3行(USER_ID)表。我在USERS_LIST(USERS_LIST_ID)表中有1行,並在連接表USERS_LIST_USERS(USER_ID,USERS_LIST_ID)3行中有1行。
我想在第3步中實現的是如下:當我從表中刪除一個用戶USERS - 假設USER_ID = 4的用戶,我只想從聯接表刪除USER_ID = 4的行,其他人留下。
有沒有註解解決我的問題?
deleteWithHibernate看起來像什麼方法? – 2009-08-19 12:00:37