在hibernate中无法更新多对多的关系

时间:2013-05-06 17:54:15

标签: database hibernate many-to-many

这是我的pojo,用户和书籍

@Entity
public class User {
private int id;
private String username;
private String userage;
private String useremail;
private String usergender;
private Set<Book> books = new HashSet<Book>();

@Id
@GeneratedValue
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public String getUserage() {
    return userage;
}
public void setUserage(String userage) {
    this.userage = userage;
}
public String getUseremail() {
    return useremail;
}
public void setUseremail(String useremail) {
    this.useremail = useremail;
}
public String getUsergender() {
    return usergender;
}
public void setUsergender(String usergender) {
    this.usergender = usergender;
}

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name="user_book")
public Set<Book> getBooks() {
    return books;
}
public void setBooks(Set<Book> books) {
    this.books = books;
}
public void addBooks(Book book) {
    getBooks().add(book);
}
public void removeBooks(Book book) {
    getBooks().remove(book);
}
}

@Entity
public class Book {
private int bookid;
private String bookname;
private String bookauthor;
private String bookstatue;
private Set<User> users = new HashSet<User>();

@ManyToMany(mappedBy="books", fetch = FetchType.EAGER)
public Set<User> getUsers() {
    return users;
}
public void setUsers(Set<User> users) {
    this.users = users;
}
@Id
@GeneratedValue
public int getBookid() {
    return bookid;
}
public void setBookid(int bookid) {
    this.bookid = bookid;
}
public String getBookname() {
    return bookname;
}
public void setBookname(String bookname) {
    this.bookname = bookname;
}
public String getBookauthor() {
    return bookauthor;
}
public void setBookauthor(String bookauthor) {
    this.bookauthor = bookauthor;
}
public String getBookstatue() {
    return bookstatue;
}
public void setBookstatue(String bookstatue) {
    this.bookstatue = bookstatue;
}
}

在Dao文件中:我想进行以下操作:

public boolean userReturnBookInDB(Book bookBean, User userBean) {
    // TODO Auto-generated method stub
    boolean remove;
    try {
        begin();
        ***userBean.removeBooks(bookBean);***       
        getSession().save(userBean);
        commit();
        remove = true;
    }
    catch (Exception e) {
        remove = false;
    }
    finally {       
        close();
    }
    return remove;
}

我可以成功地添加书籍,但是当我尝试删除书籍时,联接表中的成员不会改变。希望有人能帮助我。

1 个答案:

答案 0 :(得分:0)

在User类的以下属性书中,您需要添加orphanRemoval = true以在保存用户时删除孤儿。

@ManyToMany(mappedBy="books", fetch = FetchType.EAGER,orphanRemoval=true)
public Set<User> getUsers() {
    return users;
}