Switch Gorm to different datasource at runtime

1.1k views Asked by At

Given a need to fetch data from multiple environments (prodA, prodB etc), I created specific dataSource entries in DataSource configuration file.

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 Domain class:

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
}

In the above domain class, datasource is hardcoded to one of the environment specific datasource (prodA or prodB or even some other environment).

At runtime, I need to use this Domain class to fire findBy methods against specific database based on the request parameters (which specifies the environment type (prodA vs prodB etc).

How do I switch the domain class to use specific datasource at runtime?

1

There are 1 answers

2
MKB On BEST ANSWER

You can provide a list of data sources you want to connect through this domain, like

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

or make this domain available to all the data sources, like

static mapping = {
    datasources 'ALL'
 }

And you can query against any data source by mentioning its name in the query, like

def result1 = Foo.lookup.findByFoo(foo)
def result2 = Foo.auditing.findByFoo(foo)

Ref. multipleDatasources