java - JPA - 合并后没有任何反应

标签 java jpa many-to-many

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

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/

相关文章:

java - 在 Tomcat 启动时执行 JSP

java - JPA EntityManager 删除数据库中的所有记录

sql - 在创建 SQL 关系时感到困惑

python - 在 Django/REST 中保存多对多模型?

java - 如何将尾部斜杠 [/] 解析为 Struts 2 中的 URL

javax.net.ssl.SSLHandshakeException : Received fatal alert: unknown_ca

java - 如何使用 java 8 流对对象进行排序

java - 使用 JPA 并发访问同一文件

java - JPA(Hibernate、EclipseLink)映射 : why doesn't this code work (chain of 2 relationships using JPA 2. 0,@EmbeddedId 复合 PK-FK)?

sql - 如何在 PostgreSQL 中实现多对多关系?