Grails GORM: How do I create a composite primary key and use it for a table relationship?

前端 未结 3 596
执念已碎
执念已碎 2021-01-22 01:26

I have two tables, one of which (legacy table: A) has two fields that should serve as a composite foreign key and the other one (new table: B) should use a composite primary key

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-22 01:36

    import org.apache.commons.lang.builder.HashCodeBuilder
    class Person implements Serializable {
    
    String firstName
    String lastName
    
    boolean equals(other) {
        if (!(other instanceof Person)) {
            return false
        }
    
        other.firstName == firstName && other.lastName == lastName
    }
    
    int hashCode() {
        def builder = new HashCodeBuilder()
        builder.append firstName
        builder.append lastName
        builder.toHashCode()
    }
    
    static mapping = {
        id composite: ['firstName', 'lastName']
    }
    }
    

    this is what you can find from official docs of grails,

    http://grails.org/doc/latest/guide/GORM.html#compositePrimaryKeys

    just blindly follow this and your problem will be solved. for explanation refer above link

提交回复
热议问题