1

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
Mayank
  • 89
  • 8

3 Answers3

1

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.

th3morg
  • 4,321
  • 1
  • 32
  • 45
  • It's not a new object. The object is being created using values from db so most fields have value and some are null. Apparently validator doesn't run when fetching rows. Employee.read(id) doesn't fire validator. – Mayank Mar 21 '14 at 16:00
  • afterLoad did the trick. onLoad which is effectively beforeLoad gets overwritten by db value. Accepting answer. – Mayank Apr 08 '14 at 19:12
  • Thanks Mayank - Glad I guided you in the right direction. I updated the answer to afterLoad to make it clearer for readers. – th3morg Apr 08 '14 at 19:33
0

I think you can do this with HQL:

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

See this SO Question.

Community
  • 1
  • 1
grantmcconnaughey
  • 10,130
  • 10
  • 37
  • 66
  • It's already domain object and not a specific query. I just used query as an example to clarify what I am trying to achieve. – Mayank Mar 20 '14 at 21:34
0

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

Ashish Joseph
  • 1,103
  • 3
  • 12
  • 35