Search code examples
grailsgrails-orm

Grails/GORM Employee Salary


I'm new to Grails and I'm trying to develop a web app. I was making pretty decent progress until I ran into an issue with adding a new employee with new salary. I have a Person domain class, an Employee domain class, and a Salary domain class. All of them are listed below.

class Person {
 String firstName, lastName
 String email
 String phoneNumber
 Employer employer 

 }

class Employee extends Person {
 Date birthdate
 JobTitle jobTitle 

 static hasMany = [salary: Salary]

}

class Salary {
 Employee employee
 double salary
 Date from_date
 Date to_date

Now when I create a new employee, I can't add in a new salary just for that person, only for the employees that are already in the DB. Any help will be appreciated!


Solution

  • By looking at your code, I can presume that Salary should contain a Person's identifier, instead of Employee.

    class Salary {
      Person person
      double salary
      Date from_date
      Date to_date
    }
    

    On the other hand, if you want Employee to be in the relationship with Salary, then the hasMany property should be:

    class Person {
      String firstName, lastName
      String email
      String phoneNumber
      Employer employer 
    
    }
    
    class Employee extends Person {
      Date birthdate
      JobTitle jobTitle 
    
      static hasMany = [salary: Salary]
    }
    
    class Salary {
     Employee employee
     double salary
     Date from_date
     Date to_date
    }
    

    Keep in mind that these changes will affect your DB. I recommend taking a look at DB Migration.