Grails 2 multiple dynamic datasources in services

前端 未结 4 1003
情歌与酒
情歌与酒 2020-12-14 22:37

I am working on a Grails application where I must access several datasources. The datasources are defined in the default database (ie. they are stored there and I must make

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 23:10

    You can add multiple data sources in a single application, and access them in the services.

    Firstly you need to add basic data sources in the resources.groovy.

    first import BasicDataSource

    import org.apache.commons.dbcp.BasicDataSource;
    

    Then

        switch (grails.util.GrailsUtil.environment) {
        case "development":
            firstDataSource( BasicDataSource ) {
                driverClassName = "net.sourceforge.jtds.jdbc.Driver"
                url = "jdbc:jtds:sqlserver://localhost:1433;DatabaseName="
                username = "sa"
                password = "root"
                String SqlServerInstance = "SQLEXPRESS";
                url = url + ";" + SqlServerInstance;
            }
            break
    
        case "test":
            firstDataSource( BasicDataSource ) {
    
                driverClassName = "net.sourceforge.jtds.jdbc.Driver"
                url = "jdbc:jtds:sqlserver://localhost:1433;DatabaseName="
                username = "sa"
                password = "root"
                String SqlServerInstance = "SQLEXPRESS";
                url = url + ";" + SqlServerInstance;            }
            break;
    
    }
    

    In the same way you can add more data sources, above code will give you one more datasource to access other than the default one. I used switch to configure same data source for the different environments, same way more can be added.

    and in the service it can be accessed in the services as:

    BasicDataSource firstDataSource;
    Connection con = firstDataSource.getConnection();
    

    and then connection object can be used.

    I think it should help

提交回复
热议问题