简体   繁体   中英

Hibernate ManyToMany doesn't update

Here's an example:

@ManyToMany(targetEntity = Book.class,fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public List<Book> getBooks() {
    return books;
}

And in the other class :

@ManyToMany(targetEntity= Reader.class, fetch = FetchType.EAGER,cascade = CascadeType.ALL, mappedBy = "books")
@JoinTable(name="book_reader",joinColumns=@JoinColumn(name="id_reader",referencedColumnName="id_reader"),inverseJoinColumns=@JoinColumn(name="id_book",referencedColumnName="id_book"))
public List<Reader> getReaders() {
    return readers;
}

I want to update new readers after saving a book. But it doesn't work.

book.setReaders(readers);

then

getSessionFactory().getCurrentSession().update(book);

How can i solve this problem?

In many-to-many , you need to set both way.

For ex

books.setReaders(readers);

for(Reader reader:readers)
    reader.getBooks().add(book);

and then update it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM