Saturday, June 16, 2018

Grails on Groovy > Bind Metamethod of Hibernate Criteria Builder > Create Custom Function / Custom Method Under HibernateCriteriaBuilder > HibernateCriteriaBuilder Meta Method

To bind custom method with hibernate criteria builder you first need to create a groovy file named HibernateCriteriaListener like below:
package com.pkm

import grails.util.Holders
import org.codehaus.groovy.grails.commons.GrailsApplication
import org.grails.datastore.mapping.core.Datastore
import org.grails.datastore.mapping.engine.event.*
import org.springframework.context.ApplicationEvent
import grails.orm.HibernateCriteriaBuilder

class HibernateCriteriaListener extends AbstractPersistenceEventListener {
    protected HibernateCriteriaListener(Datastore datastore) {
        super(datastore)

        HibernateCriteriaBuilder.metaClass.myMethod = { info, value = null ->
            println("NAME=${info} VALUE=${value}")
        }
    }

    @Override
    protected void onPersistenceEvent(AbstractPersistenceEvent event) {

    }

    @Override
    boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
        return false
    }

    static void initialize(GrailsApplication application) {
        application.mainContext.eventTriggeringInterceptor.datastores.each { k, datastore ->
            Holders.applicationContext.addApplicationListener(new HibernateCriteriaListener(datastore))
        }
    }
}
Now we need to register the above functionality from BootStrap, so you need to do following:
import com.pkm.HibernateCriteriaListener
import org.codehaus.groovy.grails.commons.GrailsApplication
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
import org.hibernate.dialect.function.SQLFunctionTemplate
import org.springframework.context.ApplicationContext

class BootStrap {
    def init = { servletContext ->
        ApplicationContext applicationContext = servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
        GrailsApplication application = (GrailsApplication) applicationContext.getBean("grailsApplication")

        /* REGISTER HIBERNATE EVENT LISTENER */
        HibernateCriteriaListener.initialize(application)
    }

    def destroy = {

    }
}
And finally you can use custom criteria method using below sample:
Table1.createCriteria().list {
    delegate.myMethod("name", "value")
}

No comments:

Post a Comment