1
votes

I am new to grails and am currently trying to map an Employee class. Each employee may or may not have a manager. Also, each employee (if he is a manager) will have a list of subordinates. Mapping to this extent was relatively easy with the hasMany and belongsTo static arrays. However, my example has an additional complexity. I have 3 columns in my employee class:

  • id (the primary key)
  • ldapId (The id from the legacy ldap system)
  • managerLdapId (The manager relationship id from the legacy system).

My Employee class as of now looks like this -

class Employee {
    String firstname
    String lastname
    String email
    String ldapId
    Employee manager

    static hasMany = [subordinates: Employee]
    static belongsTo = [manager: Employee]
}

The problem is that I want to map my hasMany relationship using the ldapId field but grails defaults it to the id field. I could have made the ldapId field as the primary key but the id field also exists and it is the natural primary key for this table.

I know that hibernate had an option we could specify while defining the many-to-one relationships. It was the property-ref attribute which allowed mapping of the relationship to a column other than the primary key. Is such a property available for grails? If so, how can it be implemented?

To summarize, I need to know how to map hasMany relationships with a key other than the primary key for that table.

1

1 Answers

0
votes

I think so:

class Employee {
  String firstname
  String lastname
  String email
  String ldapId
  Employee manager

  static hasMany = [subordinates: Employee]
  static belongsTo = [manager: Employee]

  static transients = ['getId', 'setId']

  def getId() { ldapId }
  def setId(id) { this.ldapId = id }

  static mapping = {
    table 'Employee'
    id generator:'assigned', name:'ldapId', type:'string'
    ...
  }
}

Do not forget to make ldapId unique