此问题已部分回答 here但是动态引用默认数据源仍然存在问题。
我正在开发一个内部应用程序,它允许开发人员修改我们的 Multi-Tenancy 应用程序之一的配置设置,并将这些设置从开发人员推送到测试、暂存和生产。
其中每一个都有自己的数据源,并且 Grails 应用程序将安装在每个开发人员的计算机上。
本地数据源将是默认的,然后 dataSource_testing、dataSource_staging 等将引用适当的环境。
我可以使用以下内容动态引用远程数据源:
def setting = Setting."${params.environmnet}".get(id)
但是,如果
params.environment
正在引用默认数据源,此代码不再有效。在设置域类的文档中,它指出:
If a domain class uses the default DataSource and one or more others, use the special name 'DEFAULT' to indicate the default DataSource
见 the documentation
这看起来在定义您的域类适用于哪些数据源时有效,但不能引用您的域类,如:
def setting = Setting.DEFAULT.get(id)
.您收到一条错误消息:
No such property: DEFAULT for class...
我真的不想重新设计应用程序,以便不真正使用默认数据源,然后创建一个新的
dataSource_local
数据源。如果我能避免这种情况,那就太好了,因为这意味着更新仅适用于本地数据源的代码堆栈。所以我的问题......有没有办法动态引用默认数据源?
最佳答案
目前不支持它,但您可以做一些技巧来添加缺少的元方法 (getDEFAULT)。
如果您认为这是一个重要特性,您可以在 Grails Jira 上提出特性请求问题。通过添加用于查找给定数据源的所谓 GormStaticApi 实例的单独方法来支持静态访问 (CompileStatic) 可能是有意义的。请向 Grails Jira 添加功能请求,以便它解释您的用例。
现有实现会跳过 DEFAULT 数据源:
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
和 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
解决方法是将以下类保存在 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
}
}
}
}
关于Grails 2.4.2 - 动态引用默认数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24543726/