Grails 2.4.2 - Dynamically referencing default datasource

余生颓废 提交于 2019-12-04 09:21:37

It's currently not supported, but you can do some hacks to add the missing metamethod (getDEFAULT).

You can do a feature request issue on Grails Jira if you think this is an important feature. It might make sense to support static access (CompileStatic) by adding a separate method for looking up the so called GormStaticApi instance for the given datasource. Please add a feature request to Grails Jira so that it explains your use case.

existing implementation skips the DEFAULT datasource:

The logic for Hibernate4: https://github.com/grails/grails-data-mapping/blob/f9da9fe/grails-datastore-gorm-hibernate4/src/main/groovy/org/codehaus/groovy/grails/orm/hibernate/cfg/HibernateUtils.groovy#L122-L125 and Hibernate3: https://github.com/grails/grails-data-mapping/blob/f9da9fe/grails-datastore-gorm-hibernate/src/main/groovy/org/codehaus/groovy/grails/orm/hibernate/cfg/HibernateUtils.groovy#L121-L124

The workaround is to save this following class in grails-app/conf/WorkaroundsBootStrap:

import org.codehaus.groovy.grails.commons.DomainClassArtefactHandler
import org.codehaus.groovy.grails.commons.GrailsApplication
import org.codehaus.groovy.grails.commons.GrailsClass
import org.codehaus.groovy.grails.commons.GrailsDomainClassProperty
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil
import org.codehaus.groovy.grails.orm.hibernate.cfg.HibernateUtils

class WorkaroundsBootStrap {
    GrailsApplication grailsApplication
    def dataSource
    def transactionManager
    def hibernateDatastore

    def init = { servletContext ->
        def datasourceName = GrailsDomainClassProperty.DEFAULT_DATA_SOURCE
        for(GrailsClass grailsClass in grailsApplication.getArtefacts(DomainClassArtefactHandler.TYPE)) {
            def dc = grailsClass
            if (GrailsHibernateUtil.isMappedWithHibernate(dc) && GrailsHibernateUtil.usesDatasource(dc, datasourceName)) {
                HibernateUtils.registerNamespaceMethods dc, hibernateDatastore, datasourceName, transactionManager, grailsApplication
            }
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!