Trying...
Trying...

Reputation: 137

Cayenne 4.1 - Single Runtime with Multiple Datanodes with different URL and credentials

I have 2 different databases being used by one application. In the xml file, I can declare 2 nodes with different URLs and credentials without a problem.

Is there a way to do this in the code? Without creating 2 runtimes.

Upvotes: 0

Views: 108

Answers (1)

andrus_a
andrus_a

Reputation: 2563

It is possible to do via properties wrapped in a module:

ServerRuntime.builder()
  .addModule(b -> ServerModule.contributeProperties(b)
    .put("cayenne.jdbc.url.project.node1", "jdbc:url1")
    .put("cayenne.jdbc.url.project.node2", "jdbc:url2")
    // similarly add properties for driver, user, password, etc.
  )
  .build();

Alternatively for each DataNode in the Modeler you can set a custom "DataSource Factory", pointing it to your own Java class similar to this:

public class MyDataSourceFactory implements DataSourceFactory {
    
    @Override
    public DataSource getDataSource(DataNodeDescriptor nd) throws Exception {
        DataSourceInfo info = nd.getDataSourceDescriptor();

        // use the configuration in the DataSourceInfo and/or supplement it 
        // your own values
        ...

        // Create a DataSource
        Driver driver = (Driver)objectFactory.getJavaClass(driverClass).newInstance();
        return DataSourceBuilder
            .url(url)
            .driver(driver)
            .userName(username)
            .password(password)
            .pool(minConnections, maxConnections)
            .maxQueueWaitTime(maxQueueWaitTime)
            .validationQuery(validationQuery)
            .build();
    }
}

Upvotes: 1

Related Questions