JPA - 合并后没有任何反应

JPA - Nothing happens after merge

有人能告诉我为什么合并实体时没有任何反应吗?

User.java(实体)

@ManyToMany(mappedBy="users", targetEntity=Books.class,cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}) 
private List<Books> books;

Books.java(实体)

@ManyToMany (targetEntity = User.class,cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
private List<User> users;

returnBookServlet.java

int userId = (int) session.getAttribute("userId");
String stringIdBook = request.getParameter("idBook");
UserDAO daoUser = (UserDAO) request.getAttribute("userDao");
User user = daoUser.getUser(userId);
List<Books> booksOrderedByUser = user.getBooks();

for (Books x : booksOrderedByUser) {
    String idBookString = Integer.toString(x.getIdBook());
    if (idBookString.equals(stringIdBook)) {
        booksOrderedByUser.remove(x);
        break;
    }
}

user.setBooks(booksOrderedByUser);
entityManager.getTransaction().begin();
entityManager.merge(user);
entityManager.flush();
entityManager.getTransaction().commit();
entityManager.close();

在 foreach 循环之前和之后,我通过 System.out.println() 显示列表,它正确地删除了选择的书,但数据库中没有任何反应,我做错了什么?

在用户实体中所做的更改不会与您的数据库同步,因为用户实体是双向多对多关系的非拥有方。 您在 User 实体中使用 mappedby="users",因此所有者端是 Book 实体。

如果您更改 ManyToMany 的拥有方,您的代码应该可以工作,在 ManyToMany 双向关系中,您可以选择哪一方是您的拥有方(来自 JPA 2.1 规范):

Every many-to-many association has two sides, the owning side and the non-owning, or inverse, side. If the association is bidirectional, either side may be designated as the owning side. If the relationship is bidirectional, the non-owning side must use the mappedBy element of the ManyToMany annotation to specify the relationship field or property of the owning side.

然后,如果您想使用相同的代码,请将注释更改为:

User.java(实体)

@ManyToMany(targetEntity=Books.class,cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}) 
private List<Books> books;

Books.java(实体)

@ManyToMany (mappedBy="books",targetEntity = User.class,cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
private List<User> users;