Search code examples
grailsgroovynamed-query

Dynamic namedQueries


Is their a dynamic namedquery on grails? Im not sure if its the right term but, I mean a namedquery that can be true to all.

Something like:

namedQueries = {
 dynamicQuery{ term, name, value ->
   term(name, value)
 }
}

Then it can be called maybe like but not exactly:

def testClass = TestClass.dynamicQuery('eq', 'lastname', 'Bill').list()

and so you call it too like:

def testClass = TestClass.dynamicQuery('gt', 'id', 12).list()

This one might not work but is their something similar in grails?

UPDATE The idea is that so I can chained it as many as I want like:

 def testClass = TestClass.dynamicQuery('gt', 'id', 12).dynamicQuery('eq', 'stat', 11).list()

This is so that I dont have to create many namedqueries. I was hoping I can create one and use it multiple times.


Solution

  • Grails' createCriteria method generates Grails HibernateCriteriaBuilder instance, within which you can call invokeMethod method to dynamically create query criteria, which usually is defined by the standard DSL.

    Here is a example in some controller:

    private String dynamicCriteriaTest(String term, name,  value) {
        def c = TestClass.createCriteria()
        def param = []
        param << name
        param << value
        def result =  c.list{
            c.invokeMethod(term, param as Object[])
        }
        return result.toString()
    } 
    
    def test() {
        render dynamicCriteriaTest('eq','lastname','Bill')
    }
    

    That will get something you want.


    update

    If you want to call this method multiple times, pass the criteria parameters in an a List then execute the query:

        private List dynamicCriteriaTest(List param) {
            def c = TestClass.createCriteria()
            def paramList = param.collate(3)    //split the parameters into groups
            def result =  c.list{
                paramList.each { paramInstance ->
                    def command = paramInstance[0]
                    paramInstance.remove(0)
                    c.invokeMethod(command, paramInstance as Object[])
                }
            }
            return result
        }
    
        def test() {
            ArrayList param = new ArrayList()
                //the 1st criteria
            param << 'gt'
            param << 'id'
            param << (long)12    //you have to check the Grails [HibernateCriteriaBuilder] API to make sure the parameter passed to `invokeMethod` is in the right type (e.g. **long** in this case)
    
                //the 2nd one
            param << 'eq'
            param << 'stat'
            param << (long)11
    
                //even more
            param << 'like'
            param << 'description'
            param << 'some text%'    
    
            render dynamicCriteriaTest(param)
        }