Grails withCriteria, or a quick way to sort in a given order

The database function returns the id of all events in a certain radius, ordered by their distance.

Subsequently, in order to maintain performance, I eagerly download the necessary collections in the withCriteriafollowing way:

    def events = Event.withCriteria {
        'in'('id', ids)
        fetchMode("someRelation", FetchMode.JOIN)
        // a few more joins
        setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
    }

However, this will ruin the order. I noticed that the result of this criteria query returns all events sorted by id. Which makes some sense, since it indoes not guarantee any special order (and it makes no sense that it should). However, this is a small problem, as I want this list to be ordered.

So, I did this:

    List<Event> temp = [];
    ids.each { id -> temp << events.find { it.id == id } }
    events = temp;

, ~ 2400 , 1 , .

, ?

+1
1

, ( ):

SQL

, Postgres, mysql, , . , , , - : !

ORDER BY (ID=10, ID=2, ID=56, ID=40) DESC

SQL- Grails, ,

Groovy ( )

// only four id, for the sake of simplicity
def ids = [10, 2, 56, 40];

// get your events with your criteria
def events = Event.withCriteria {
    'in'('id', ids)
    fetchMode("someRelation", FetchMode.JOIN)
    // a few more joins
    setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
}

// create an array that maps event.id -> sortedEventIndex
def indexToIdArray = [];
// event with id 2 is at index 1
// event with id 10 is at index 0 
// ...
// [null, null, 1 , null, null, null, null, null, null, null, 0, ...]
ids.eachWithIndex{ num, idx -> indexToIdArray[$num] = $idx }

def sortedEvents = [];
events.each { ev -> sortedEvents[indexToIdArray[ev.id]] = ev }

, O (n), . , , .

. , groovy.

, . -, , ( ).

, ,...

, ( /):

  • ,
  • ( p1, p1 )

, .

+1

Source: https://habr.com/ru/post/1785398/


All Articles