grailsgrails-domain-classgrails-validation

grails validation when fetching rows


Is it possible to fetch a default value in grails if a column is null? If I were to represent following query via grails domain object then how could I achieve it:

SELECT IFNULL(empsalary,0.00) from Employee;

Domain object:

class Employee{
   Integer id,
   Float empsalary

   static constraints = {
      id unique: true, blank:false
      empsalary nullable:true
   }
}

Solution

  • If you want a default value to come out of the database without having to code anything into your classes, I suggest you update every row where it is null and set it to 0 in the database. If data is getting inserted from another application and that application is allowing a null value, put a 'DEFAULT 0' on your database column.

    Grails also offers an "afterLoad" event which is run when a domain object gets loaded from the database. See the documentation here: http://grails.org/doc/2.3.7/guide/GORM.html.