grails - 在运行时将 Gorm 切换到不同的数据源

标签 grails grails-orm grails-domain-class

鉴于需要从多个环境(prodA、prodB 等)获取数据,我在 DataSource 配置文件中创建了特定的 dataSource 条目。

environments {
    development {
         dataSource_prodA_oracle {
            dbCreate = "none"
            url = "jdbc:oracle:thin:@//prodA.box.url.com:1521/prodADB"
            driverClassName = "oracle.jdbc.OracleDriver"
            username = "prodA_user"
            password = "horribly_encoded_password"
            passwordEncryptionCodec = PropertiesCodec
        }
        dataSource_prodB_oracle {
            dbCreate = "none"
            url = "jdbc:oracle:thin:@//prodb.box.url.com:1521/prodBDB"
            driverClassName = "oracle.jdbc.OracleDriver"
            username = "prodB_user"
            password = "another_horribly_encoded_password"
            passwordEncryptionCodec = PropertiesCodec
        }
    }
}

Gorm 域类:
class Foo {
    static mapping = {
        version false
        datasource 'prodA_oracle' //needs dynamic datasource behavior
        createdDate type: Date, column: 'created_date'
        id generator:'assigned', name:'fooId', type:'string'
    }
    static constraints = {
    }
    String fooId
    String region
    Date createdDate
}

在上述领域类中,数据源被硬编码为环境特定数据源之一(prodA 或 prodB 甚至其他环境)。

在运行时,我需要使用这个 Domain 类来触发 findBy基于请求参数(指定环境类型(prodA 与 prodB 等))针对特定数据库的方法。

如何在运行时切换域类以使用特定数据源?

最佳答案

您可以提供要通过此域连接的数据源列表,例如

static mapping = {
    datasources(['lookup', 'auditing'])
}

或使该域可用于所有数据源,例如
static mapping = {
    datasources 'ALL'
 }

您可以通过在查询中提及其名称来查询任何数据源,例如
def result1 = Foo.lookup.findByFoo(foo)
def result2 = Foo.auditing.findByFoo(foo)

引用。 multipleDatasources

关于grails - 在运行时将 Gorm 切换到不同的数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30871537/

相关文章:

unit-testing - 为什么添加grails服务单元测试会破坏 Controller 单元测试?

grails - Grails 2 Spring Core插件-服务器请求基于密码的身份验证,但未指定密码

grails - 两个grails应用程序均使用springSecurity,一次登录即可访问两者

Grails hasOne 关联

hibernate - Grails GORM 刷新忽略获取策略

grails - 使用 findAllBy 方法访问对象的属性列表时出现问题

hibernate - 在字段 'objname'上对象:'fieldname'中引起的错误:拒绝的值[null];

maven - Grails 2.3依赖管理Maven或BuildConfig

spring - chalice 3;使用 Spring Security 查看自己的数据

grails - 域类 hasMany 添加条目失败