Search code examples
grailsdata-bindingmappinggrails-ormhibernate-mapping

Grails - Mapping and Data Binding multiple collections of the same Domain Class


I have a domain class (let's call it security) and it needs three "one to many" relationships with another domain class (let's call it role). The three relationships are "current", "previous", and "new".

Basically I'm hoping to do something like this (in reality it's more complicated, but this will do to illustrate things):

class Security
{
  static hasMany = [current: Role, previous: Role, new: Role]

  Set current
  Set previous
  Set new
}

class Role
{
  static belongsTo = [security: Security]

  String name
}

Unfortunately something like this doesn't work since the Role domain class maps to only one table and that one table has only one column for the Security class' ID.

Is this possible without creating three separate Role classes and instead just map one class to multiple tables?

I'm also looking at the possibility of simply including a flag in the Role class to signal whether the role is current, previous, or new and only having one "one to many" relationship in the Security class. However, this approach is causing issues with data binding, since my HTML form would need to send two pieces of information for each role (the name property and also the type). Since these roles are listed in a HTML select statement I can only send one piece of information (the name).


Solution

  • If you do not depend on the belongsTo in Role (you have to remove it) you can use joinTable:

    class Security {
        static hasMany = [current: Role, previous: Role, next: Role]
    
        static mapping = {
            current joinTable: [name:'current']
            previous joinTable: [name:'previous']
            next joinTable: [name:'next']
        }
    }