为连接到另一个域的复合主键的外键创建Grails域映射

时间:2015-07-14 02:38:54

标签: grails groovy

如何将Grails Domain的两列(也是其复合主键)引用到另一个Domain类的复合主键?在这种情况下,CEOAgencyAgencyBranch之间存在一对一的关系。

我可以轻松地将CEO映射到Agency,因为它只涉及一列:CEO.id == Agency.ceo_id。但我无法使用以下两列将Branch映射到AgencyAgency.id == Branch.agency_id and Agency.main_branch_id == Branch.branch_id

class CEO {
    .....
}

class Agency {
    .....
    CEO ceo
    Branch mainBranch

    static mapping = {
        .....
        ceo column: 'ceo_id'
        /* Tried using this mapping but it doesn't work
        mainBranch {
            agencyId column: 'id',
            branchId column: 'main_branch_id'
        }
        */
        .....
    }
}

class Branch {
    .....
    Integer agencyId
    Integer branchId

    static mapping = {
        .....
        id composite: ['agencyId', 'branchId']
        .....
    }

    static constraints = {
        .....
        branchId unique: 'agencyId'
        .....
    }
}

1 个答案:

答案 0 :(得分:1)

请尝试使用以下技术代理类:

 class Agency {
     .....
     CEO ceo
     Branch mainBranch

     static mapping = {
     .....
     ceo column: 'ceo_id'
     columns {
        mainBranch {
            column name: "FirstName"
            column name: "LastName"
        }
     }
 .....
 }

参考是here - 第6.5.2.5节复合主键。