title: Grails Domain Update vs Database Trigger Update
body: <p>I have 2 tables, first one is parent table and second one is child table.</p>
  
  <pre><code>Table Employee:
  Emp_Id, Name, Age, Salary, Travel_Allowance, Cost_To_Company
  
  Table Allowance:
  Id, Emp_Id, Type, Amount
  </code></pre>
  
  <p>Here I need to update Travel_Allowance column of Employee table whenever a row inserted/updated for Travel_Allowance type record in Allowance table.</p>
  
  <p>For this I have written a trigger on Allowance table to update Employee table Travel_Allowance column whenever an insert/update performed on Travel_Allowance type record.</p>
  
  <p>Trigger:</p>
  
  <pre><code>CREATE TRIGGER [trig_updateEmployeeOnAllowanceUpsert]
  ON [Allowance]
  FOR INSERT,UPDATE
  AS
  
  UPDATE Employee SET Travel_Allowance = i.amount
  FROM Employee e 
  INNER JOIN INSERTED i ON e.emp_id = i.emp_id
  AND i.type = 'TravelAllowance';
  </code></pre>
  
  <p>In Grails, my code will be as below:</p>
  
  <pre><code>class Employee {
      String name
      Integer age
      BigDecimal salary
      BigDecimal travelAllowance
      BigDecimal costToCompany
      static hasMany = [allowances: Allowance]
  }
  
  class Allowance {
      Employee employee
      BigDecimal amount
  
      static belongsTo = [employee: Employee]
  }
  </code></pre>
  
  <p>A) Prepares Allowance objects and adds them to Employee object like-</p>
  
  <pre><code>def updateAllowances(def employeeId, def allowanceAmount) {
      Employee emp = Employee.get(employeeId)
      Allowance a = new Allowance()
      a.employee = emp
      a.amount = allowanceAmount
      emp.addToAllowances(a)
  
      // Calculate Cost To Company
      def newCost = 0
      emp.alowances.each { allowance -&gt;
          newCost += allowance.amount
      }
      emp.costToCompany = newCost + emp.salary;
      emp.save(flush:true, failOnError: true)
  }
  </code></pre>
  
  <p>Above code is working fine when updating existing Travel_Allowance type record. But while adding new Travel_Allowance type record this is not working as expected.</p>
  
  <p>While adding a new Travel_Allowance type record, trigger is updating Employee table with the new Allowance record amount. Then Grails overriding the same record with previous value in Travel_allowance column.</p>
  
  <p>How to make Grails not to override the value updated from Database trigger?</p>