Question

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
   }
}
  • making empsalary nullable false isn't an option due to existing data
  • validator on empsalary seems to work when inserting rows but not while data fetch
  • we can consider writing say getEmpSalary() method on domain and perform check there but there are several other fields we need to do this so trying to avoid massive code changes
Was it helpful?

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.

OTHER TIPS

I think you can do this with HQL:

def salary = Employee.executeQuery('SELECT COALESCE(empsalary, 0.0) FROM Employee')[0]

See this SO Question.

Please try setting Float empsalary = 0.0 in your domain object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top