psms
psms

Reputation: 883

Grails: How to make a foreign key as primary key

I have 2 domain classess; A and B.

class A {

    Long a_id

    static constraints = {
    }

    static mapping = {
        id name:'a_id'
    }
}

Class B {

    A a

    static constraints = {
    }

    static mapping = {
        id name:'a',  generator: 'assigned'
    }

}

In domain B, I want to make 'a' as the primary key and also as the foreign key(referencing to A.a_id)

The above code is not working. Please help me.

Upvotes: 1

Views: 743

Answers (2)

Roland Vassallo
Roland Vassallo

Reputation: 1

The 'composite' mapping doesn't require multiple property names. Providing a single property name corresponding to another domain class generates the correct schema to use the foreign key as the primary.

The foreign domain must implement Serializable to use the composite mapping

Class B implements Serializable { 
    A a

    static mapping = {
         id composite: ['a'] // Generates a column named 'a_id' and primary key index
    }
}

Upvotes: 0

Sudhir N
Sudhir N

Reputation: 4096

You can make it such that the primary key is always the same as the foreign key. and point the foreign key to the primary key.

Class B {

    A a

    static mapping = {
         id generator: 'foreign', params: [property: 'a']
         a insertable: false, updateable: false , column:'id'
    }

}

Upvotes: 1

Related Questions