Grails domain mapping of legacy tables that share same primary key name

196 Views Asked by At

The legacy database has two tables that use the same column name as the primary key. For example:

user:
user_id int
name string

user_profile:
user_id int
visit_count int

I would like to create a bidirectional one-to-one relationship. i.e.

class User {
    String name
    UserProfile userProfile
    static mapping = {
        id column: 'user_id'
    }
}

class UserProfile {
    Integer visitCount
    User user
    static mapping = {
        id column: 'user_id'
    }
}

I would like to be able to reference 'user.userProfile.visitCount' or 'userProfile.user.name'.

I have tried many combinations of direct references and relationship discriptors, 'hasOne', 'belongsTo', etc. I would think this is simple but cannot find the right syntax. I get duplicate column issues or missing column name issues. Any help would be appreciated. Thanks in advance.

1

There are 1 best solutions below

6
Joe On

The User in UserProfile would default to user_id which is the same as the id column for UserProfile. So just add a column name for the user reference like below.

class UserProfile {
    Integer visitCount
    User user

    static mapping = {
        id column: 'user_id'
        user column: 'useruser_id'
    }
}

class User {
    String name

    static mapping = {
        id column: 'user_id'
    }

    static hasOne = [ userProfile: UserProfile ]
}