GORM 删除操作:找到同一集合的两个表示形式


@Entity
public class Contact{
    List associations
    static hasMany[
    associations:Contact
    ]
    static mapping[
    associations cascade:"all-delete-orphan"
    ]
}

我有这样的服务Contact实体中删除关联

Contact.withTransaction{status ->
        user.contacts.collect{Contact c->
            c.associations.collect{Contact association->
                c.associations.remove(association)
            }
        }
     }

尝试这个时,我得到org.hibernate.HibernateException:Found two representations of same collection: Contact.associations

我是否犯了错误或任何其他方式从联系人中删除关联?

首先,

在这种情况下,您不应该使用 collect。 我认为适当的方法是每个。 此时您不需要使用 withTransaction,期望您将使用新的休眠会话。 试试这个:

def assocs = []
// store collection to avoid concurrent modification exception by during delection with in each   method
assocs += user.contacts.associations
assocs.each {
   // because of your cascase setting all orphans will be deleted automatically
   user.contacts.removeFromAssociations(it)
}

我认为有一种更短的方法来完成这项任务:

def contact = Contact.get(...) // retrieve a contact
contact.associations.clear() // remove all associations of the contact

如果您不熟悉 GORM,最好从这篇博文开始。

我解决了这个问题。问题是因为删除了数组中的关联。当我获得联系人列表时,它也给了我关联,因为关联也是联系人的实例。因此,首先,我通过仅获取联系人来获取带有sql查询的联系人列表,然后删除了联系人的关联。非常感谢大家,特别是Hoàng Long :)

最新更新