alexgorbatchev

Tuesday, July 11, 2017

Gorm - Sorting by calculated or derived field

Recently, while trying to work with a legacy database I needed to create a default sort on a String field that sometimes held a number. One cannot simply sort on the String field because it will produce incorrect results, such as [1, 10, 11,..., 2, 20, ...]. A simple method for correcting this is to pad the field with 0's, so that it produces the results [00001, 00002, 00010, ...]). In order to accomplish this by default in the domain class, in the domain's mapping closure simply add a formula to a sort field.

To create a default sort on a calculated or derived field

After loading a series of 20 books into GORM (GORM Book loading code below), retrieving them using Book.list() should produce [1, 2, ..., 10, 11, ..., 20]

References