我使用grails 2.0.0。我有三个对象Member,Product和ProductType。成员有很多产品,并且是一对多关系。产品指向ProductType(引用表),并且是多对一关系。我的问题是关于删除产品。它在一种情况下起作用,而在另一种情况下不起作用。继续阅读。

下面的映射的粗略概述:

Member.groovy:

class Member  {
   Long id
   ....
   SortedSet products
   static hasMany = [products:Product]
   static mapping = {
        table 'T_MEMBER'
        id column:'MEMBER_ID'...
       products cascade: "all-delete-orphan"
   }
}

Product.groovy:
class Product {
   Long id
   ProductType productType
   ...
   static belongsTo = [member:Member]
   static mapping = {
        table 'T_PRODUCT'
        id column:'PRODUCT_ID'
        member column: 'MEMBER_ID'
        productType column: 'PRODUCT_TYPE'
        ...
   }
}

ProductType.groovy:
class ProductType {
   Long id
   ..
   static mapping = {
        table 'T_PRODUCT_TYPE'
        id column:'PRODUCT_TYPE', generator:'assigned'
    ...
   }
}

我得到的客户服务代码的轮廓是...
    if((newMember.products) && (newMember.products.size() >0)) {
        def addList = newMember.products - existingMember.products
        def removeList = existingMember.products- newMember.products
        removeList.each { product ->
            existingMember.removeFromProducts(product)
        }
        addList.each {product ->
            existingMember.addToProducts(product)
        }
    }

到现在为止还挺好。这是完美的工作。但是,当我通过执行以下操作为T_PRODUCT表引入复合主键时:
   static mapping = {
        table 'T_PRODUCT'
        //id column:'PRODUCT_ID'
        id composite:['member', 'productType']
        member column: 'MEMBER_ID'
        productType column: 'PRODUCT_TYPE'
        ...
   }

我得到这个:



知道我哪里可能出问题了吗?

最佳答案

您的Product域类必须实现Serializable并覆盖方法hashCode()equals(),这必须在使用复合键的情况下完成。

您的产品域类必须是这样的

class Product implements Serializable {
        Long id
        ProductType productType
        ...

        static mapping = {
             table 'T_PRODUCT'
             id composite:['member', 'productType']
             member column: 'MEMBER_ID'
             productType column: 'PRODUCT_TYPE'
        }

        boolean equals(other) {
            if (!(other instanceof Product )) {
                return false
            }
            other.member== member && other.productType== productType
        }

        int hashCode() {
            def builder = new HashCodeBuilder()
            builder.append member
            builder.append productType
            builder.toHashCode()
        }

    }

我认为这样一切都会好起来的。

如有问题,请写。

10-06 06:09