Search code examples
sortinggrailsgroovygrails-ormsql-update

DefaultGroovyMethod sort leads to version change and database update


I have a List of domain objects which I want to sort by a specific property. Groovy provides a lot of functions to handle lists in a "simple"/"groovy" way.

The problem is that something like

myDomainList.sort{it.position}

leads to an update of version in myDomain-Table. What I want is the expected sort behavior without (any) hibernate-call (database change).

How can I achieve this?


Solution

  • sort mutates the collection it is working on unless you use it like this:

    myDomainList.sort( false ) { it.position }
    

    This variation of sort which takes 3 parameters, first being the Iterable itself, second boolean (to decide whether to mutate or create a new collection instead of mutating the original collection) and 3rd parameter being the closure.

    In the former case, when sort modifies the list then domain class is marked as dirty, hence a flush becomes imminent on transaction close.