Mxb
Mxb

Reputation: 101

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
   }
}

Upvotes: 1

Views: 300

Answers (3)

th3morg
th3morg

Reputation: 4779

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.

Upvotes: 1

Ashish Joseph
Ashish Joseph

Reputation: 1153

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

Upvotes: 0

grantmcconnaughey
grantmcconnaughey

Reputation: 10689

I think you can do this with HQL:

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

See this SO Question.

Upvotes: 0

Related Questions