How to set formula in grails domain class?
Asked Answered
O

1

3

I am trying to write formula in my domain class which helps me in creating criteria.

class MyClass {
    //some fields
    Date appointmentTime
    String ddmmyy
    int year
    int month
    int day
    static transients = [
        'ddmmyy',
        'year',
        'month',
        'day'
    ]
    static mapping= {
        ddmmyy formula('DATE_FORMAT(appointmentTime)')
        year formula('YEAR(appointmentTime)')
        month formula('MONTH(appointmentTime)')
        day formula('DAYOFMONTH(appointmentTime)')
    }
}

Whenever I am trying to use this fields in my criteria it throws error i.e. can not resolve property 'ddmmyy' of 'myClass'.

MyCriteria is:

Date myDate = Calender.instance.time

def results = MyClass.createcriteria().list{
    lt('appointmentTime', date+1)
    ge('appointmentTime', date)
    projections {
        groupProperty('ddmmyy')
        count('id')
    }
}

Any idea why I am getting an exception for this?

Openeyed answered 9/5, 2014 at 4:44 Comment(1)
Note that the formula expressed in the ORM DSL is SQL so references to other properties should relate to the persistence model not the object model, which is why the example is wrong being that it refers to appointmentTime and not APPOINTMENT_TIMEPhrase
W
5

You need to make these fields non transient to use in criteria. See reference document

http://gorm.grails.org/6.1.x/hibernate/manual/#derivedProperties

Whizbang answered 9/5, 2014 at 7:8 Comment(4)
Do you mean this fields will be persistent with DB?Openeyed
Derived properties are not persisted, at least not directly. See grails.org/doc/latest/guide/GORM.html#derivedProperties.Temporary
No it wont be if its a derived property, but it has to be non transient to be used by criteria or dynamic finder.Whizbang
@HussainFakhruddin you can update the link gorm.grails.org/6.1.x/hibernate/manual/#derivedProperties ;)Neopythagoreanism

© 2022 - 2024 — McMap. All rights reserved.