2

假设我们有一个定义如下的实体:

public class Member extends User implements Comparable<Member> {
    @ManyToMany
    @JoinTable(name = "Friends")
    @Filters({ @Filter(name = "deleted") })
    private Collection<Member> friends = new HashSet<Member>();
}

并有一个名为deleted的过滤器,没有定义类似的参数

@FilterDef(name = "deleted", defaultCondition = "deleted = 0")

当我尝试将新元素添加到持久成员对象的朋友集合中时,就会出现问题。提交事务后,会出现以下异常。

org.hibernate.HibernateException: cannot recreate collection while filter is enabled: [domain.entity.Member.friends#98304]
at org.hibernate.action.internal.CollectionUpdateAction.execute(CollectionUpdateAction.java:74)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:377)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:369)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:291)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:339)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1234)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)

任何想法我做错了什么?

4

1 回答 1

3

我有同样的问题。对我来说,这是 @ManyToMany 注释与 java.util.List 的组合。当顺序可能很重要时,Hibernate 似乎在重新创建 Collection 时遇到了问题。我认为 Hibernate 不会检查您是否实际上将 Set 或 List 放入 Collection 中,因此 Hibernate 会检查顺序。所以我知道有两种可能的方法来解决这个问题。要么你把一个额外的注释 @IndexColumn(name = "NAME_OF_THE_INDEX_COLUMN") 到你的收藏

public class Member extends User implements Comparable<Member> {
    @ManyToMany
    @JoinTable(name = "Friends")
    @Filters({ @Filter(name = "deleted") })
    @IndexColumn(name = "NAME_OF_THE_INDEX_COLUMN")
    private Collection<Member> friends = new HashSet<Member>();
}

或者如果顺序对您不重要,请将类型更改为接口 Set。

public class Member extends User implements Comparable<Member> {
    @ManyToMany
    @JoinTable(name = "Friends")
    @Filters({ @Filter(name = "deleted") })
    private Set<Member> friends = new HashSet<Member>();
}

希望这将有助于解决您的问题。

于 2013-08-22T09:23:48.977 回答