有人可以告诉我为什么合并实体时没有任何反应?
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() 显示列表,它正确地删除了所选的书籍,但数据库中没有任何反应,我做错了什么?
最佳答案
在用户实体中所做的更改不会与您的数据库同步,因为用户实体是双向多对多关系的非拥有方。 您在用户实体中使用mappedby =“users”,因此所有者方是图书实体。
如果您更改 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;
关于java - JPA - 合并后没有任何反应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34244298/