Search code examples
hibernategrailsgrails-orm

GORM id assigned to another domain class


I have an User Class and I want to create a new Class called UserSettings. The UserSettings class should be contain the User ID which also should be the ID of itself.

The UserSettings looks like this:

class UserSettings {
    String listDefaultTimePeriod = "today"
    User user
    static mapping = {

        id generator: 'assigned', name: 'user'
        user column: 'user_id'

    }
}

If I start the project I get this Error:

Caused by: org.hibernate.MappingException: Could not determine type for: User, at table: user_settings, for columns: [org.hibernate.mapping.Column(user_id)]

How can I map UserSettings correctly to use the user_id as primary key?


Solution

  • I think I didn't understand you correctly... (and stumbled now over the same question for a one-to-one association ...)

    To have "The UserSettings class should be contain the User ID which also should be the ID of itself." I found the following solution (for a one-to-one association):

    class User {
        String name
    
        static hasOne = [setting: UserSetting]
    
        static mapping = {
            id column: 'user_id'
            setting cascade: 'all-delete-orphan'
        }
    
        static constraints = {
            setting unique: true
        }
    }
    
    class UserSetting {
    
        static belongsTo = [user: User]
    
        String listDefaultTimePeriod = "today"
    
        static mapping = {
            id column: 'user_id', generator: 'foreign', params: [property: 'user']
            user insertable: false, updateable: false
        }
    
    }
    

    The link to the hibernate documentation for the "foreign" generator: hibernate generators

    And the link to a blog-post which I found, describing this solution: Grails foreign id generator