Grails - IndexBackref 的重复 属性 映射

Grails - Duplicate property mapping of IndexBackref

我在与此博客密切相关的 grails (3.1.11) 中遇到了一个奇怪的问题 post(从 2010 年开始!): http://codedumpblog.blogspot.de/2010/02/grails-many-to-many-with-lists.html

我正在尝试对以下简单关系建模:

到目前为止我有以下代码:

class Organization {
    List addresses

    static hasMany = [addresses: Address]

    static mapping = {
        addresses sort: 'country', order: 'asc', cascade: "all-delete-orphan"
    }
}

class Person {
    List addresses

    static hasMany = [addresses: Address]

    static mapping = {
        addresses sort: 'country', order: 'asc', cascade: "all-delete-orphan"
    }
}

class Address {
    String country
    //...truncated...

    static belongsTo = [organization: Organization,
                        person  : Person]

    static constraints = {
        organization nullable: true
        person nullable: true
    }
}

但是在 运行 之后我得到以下 Hibernate 异常:

org.hibernate.MappingException: Duplicate property mapping of _addressesIndexBackref found in com.example.Address

与博客 [​​=53=] 中一样,仅当 addresses 字段在 parent 类 中的名称相同时才会出现此问题。如果我将字段分别重命名为 organizationAddressespersonAddresses,那么一切都会按预期进行。

不过我希望该字段保持 addresses,这样我就不必调用 organization.organizationAddressesperson.personAddresses.

之类的东西

是否有针对这个已有近 7 年历史的问题的现代解决方法?

问题


这看起来像一个 Hibernate 错误。当您创建 Class 时发生 many-to-one

连接的两个关系

在你的例子中,hasMany

有两个 class 与 Address 相关

解决方案


use关系替换membership关系。在您的情况下,这样做是这样的:

创建一个 class ListAddresses 来保存 PersonOrganization:

的地址
class ListAddresses {
    List addresses

    static hasMany = [addresses: Address]

    static mapping = {
        addresses sort: 'country', order: 'asc', cascade: "all-delete-orphan"
    }
}

删除 Address 中的所有关系并创建新关系:

class Address {
    String country
    //...truncated...

    static belongsTo = [list:ListAddresses]
    /*static belongsTo = [organization: Organization,
                    person  : Person]*/

    static constraints = {
        /*organization nullable: true
        person nullable: true*/
    }
}

PersonOrganization

中使用ListAddresses
class Organization {
    ListAddresses addresses

    static mapping = {
        addresses cascade: "all-delete-orphan"
    }
}

class Person {
    ListAddresses addresses

    static mapping = {
        addresses cascade: "all-delete-orphan"
    }
}

此答案基于问题。但就我而言,解决方案更简单,因为我替换了 belongsTo 关系而不是 hasMany.