Search code examples
grailsgrails-orm

Grails 3 / GORM kick out single records from result


I'm trying to achieve the following in an ajax call from a text field to a Controller:

  1. Get a Motor list according to the criteria from the text field
  2. Kick out certain values out of the resulting list: Those Motors contained inside Otherdomain (and meeting a certain criteria) shall not be part of the final result

Is my approach right? What is the missing brick? Of course the number of results would be 30 minus the number of kick-out-results; it would be better though if the all-over number of lines would be exactly 30.

With this call I'm trying to reduce search time over a large number of lines in the Motor table.

def criteria =  Motor.createCriteria()
def motorlist = criteria.list {
    like ("motornumber", "%" + params.search + "%")
    maxResults(30)
    order("motornumber","asc")
}
motorlist.each { mt ->
    Otherdomain.findByMotor(mt).each { rd ->
        if (rd.kickoutCriteriaIsTrue) {
            // REMOVE MOTOR from result "motorlist" needed
        }
    }
}

response.setContentType("application/json")
render motorlist as JSON

Thank you in advance for any hint


Solution

  • After some more research on HQL and with the help of @Daniel's comment, I ended up in using this, and I'm quite happy with this:

    def reparaturstatuserledigt = Reparaturstatus.findByStatus('done')
    def hqlstring = "SELECT m " + \
        "FROM Motor m " + \
        "WHERE m.motorennummer LIKE :searchterm AND " +
            "m not in (SELECT motor FROM Reparaturdetail rd WHERE rd.motor = m and rd.detailstatus <> :detailstatus)"
    def motorlist = Motor.executeQuery(hqlstring, [detailstatus: reparaturstatuserledigt, searchterm:'%'+params.search+'%', max: 30, offset: 0])
    response.setContentType("application/json")
    render motorlist as JSON
    

    Notably, I'm using a named parameter searchterm which prevents SQL injection. With my first approach, I probably would have run into this.