Search code examples
searchgrailshqldynamic-finders

How can I make a dynamic Grails search?


Consider this domain class:

class House {
  Integer room
  Integer bathroom
  Date builtDate
  Date boughtDate

  String roadName

  String getSearch(){
    return room + " " + bathroom + " " + builtDate + " " + boughtDate
  }
}

I imagine having several fields for my search mechanism: search by room, bathroom, builtDate, boughtDate.

The user should be able to search for any combination of these paramaters. He can use only one, or all of them. I need some help with my controller code. I'm almost sure I cannot do that using HQL Dynamic Finders so I'll have to use SQLS statments.

Any help/hint would be appreciated.


Solution

  • You probably want to use a hibernate criteria. Something along the lines of:

    if (room && bathroom && builtDate && boughtDate) {
      House.withCriteria {
        if (room) {
          gte 'room', room
        }
        // ...
      }
    }
    

    Look at the docs on createCriteria and withCriteria for more information.