hibernategrailstransientcreatecriteria

Grails createCriteria and using a Transient field and PagedResultsList


Domain Fields:

startDate: Date
length: Integer
perpetuity: Boolean
expiryDate: Transient (startDate + length (in years))

Domain methods - These methods are used for filtering on a big filter form for a user to search for the 4 different expiration status'.

Date getExpiryDate() {
    if (this.startDate == null || this.length == null) {
        return null
    }

    Timestamp startDate = this.startDate;
    Calendar expirationDate = Calendar.getInstance()
    expirationDate.setTime(startDate)
    expirationDate.add(Calendar.YEAR, this.length)

    return expirationDate.getTime()
}

String getMechExpiredStatus() {
    String isExpiredString = 'Unspecified'
    Date expDate = getExpiryDate()
    if (expDate != null) {
        if (expDate < new Date()) {
            isExpiredString = 'Yes'
        } else {
            isExpiredString =  'No'
        }

    } else if (isPerpetual && startDate != null) {
        isExpiredString =  'Perpetual'
    }

    return isExpiredString
}

Building the results list

PagedResultList getMechanisms(offset, max, sortColumn, sortOrder, filters, idsOnly = false) {
    def criteria = Mechanism.createCriteria()
    def results = criteria.list(max: max, offset: offset) {
        if (idsOnly) {
            projections {
                property('id')
            }
        }

        if (filters && filters.idFilter) {
            eq('id', filters.idFilter);
        }
    ...
    }

    if (filters && filters.expiredFilter != null && filters.expiredFilter) {
        // Do Work
        // Tried getting results and removed invalid results that do not meet the 
        // expired filter selection
    }

return results

}

I cannot seem to find a way to write a createCriteria using the transient field 'expiryDate' nor using the getMechExpiredStatus method.

I've tried getting a list of items with the other filters and then removing the items that aren't valid for the expiration filter separately but the PagedResultList doesn't get updated properly; it just returns a current paged result list. I cannot find much help regarding the PagedResultList object either. Remove and Add returns a boolean for some reason. Apparently I do not understand the object very well.

If I remove the max and offset from the initial criteria list, the query takes a very long time to run.

Any ideas how I can accomplish this?


Solution

  • I solved the problem by just making the expiration status and date in a view and linked it to the domain object. Works great!