grantmcconnaughey
grantmcconnaughey

Reputation: 10689

Grails one-to-one mapping that shares an ID

I have the following domain classes in Grails 2.3.11. They are mapping to legacy database tables that can't be changed. Both classes share an id called pidm:

class Person {
    Long pidm
    String firstName
    String middleName
    Bio bio

    static mapping = {
        id name: 'pidm', generator: 'assigned'
        bio column: 'pidm'
    }
}

class Bio {
    Long pidm
    String ssn
    String gender
    Date birthDate

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

There is no separate person_id column in the Bio table or anything like that. There should be a one-to-one mapping via pidm.

Currently the only way I can get this to work is to add updateable: false, insertable: false to bio in the mapping block. What if I want to update and/or insert a Bio instance? Is there a better way for me to do this and share the pidm column as the id for the Person class AND as a reference to Bio?

Upvotes: 1

Views: 917

Answers (1)

rimero
rimero

Reputation: 2383

You'll need to make the following changes in your Bio class and related mappings :

  • Use a foreign ID generator.

  • Introduce a hasOne/belongTo bi-directional relationship

  • You also need to make sure that any linked element property is not insertable or updatable.

For a concrete example

http://blog.swwomm.com/2011/09/grails-foreign-id-generator.html

Other references

Upvotes: 3

Related Questions