org.hibernate.MappingException:未知实体:org.hibernate.collection.internal.PersistentBag

时间:2015-12-12 09:53:36

标签: java hibernate jpa many-to-many

我的代码如下:

int userId = 42;
String stringIdBook = "42";
User user = daoUser.getUser(userId);
List<Books> booksOrderedByUser = user.getBooks();

for (Books x : booksOrderedByUser) {
    System.out.println(x.getTitle());
}

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

}

for (Books x : booksOrderedByUser) {
    System.out.println(x.getTitle());
}

entityManager.getTransaction().begin();
entityManager.merge(booksOrderedByUser);
entityManager.flush();
entityManager.getTransaction().commit();

entityManager.close();

当我运行这个jpa时,我得到了这个例外:

org.hibernate.MappingException: Unknown entity: org.hibernate.collection.internal.PersistentBag
    at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1451)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:147)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:69)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:839)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:821)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:826)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:1161)
    at servlet.returnBookServlet.doPost(returnBookServlet.java:59)

此代码获取属于用户并删除所选书籍的书籍列表。第一个问题是书籍未被删除(我通过System.out.println()打印书籍列表,列表在booksOrderedByUser.remove(x.getIdBook()之前和之后相同)。第二个问题是合并期间的此异常。有人能告诉我我做错了吗?

1 个答案:

答案 0 :(得分:2)

首先,使用equals来比较字符串值,而不是==

第二件事是,您的List包含Books个对象,因此请致电:

remove(x.getIdBook())

没有机会成功。

你想要的是从列表中删除Books对象,而不是String对象或其他任何对象,所以这样做:

remove(x)

最后,您可能希望将Books课程重命名为Book,因为它只代表一本书。