2010-11-11 112 views
6

我正在grails中創建一個應該從一個數據庫讀取並寫入另一個數據庫的應用程序。我已經爲這個需求創建了datasources.groovy並安裝了datasources插件。但是,我在執行sql查詢時如何使用這個數據源(select * from .......等等)。在grails中爲應用程序使用兩個數據庫

例如,以下是我如何在我的動作中運行查詢。我正在使用自定義查詢,而不是格姆。

EDITED:

class TuneController { 

    def dataSource_ds2 

    def list = { 

     String nameSql = "select name from emp where id=3345" 
     Sql sql = new Sql(dataSource_ds2) 
     String name = sql.rows(nameSql) 
     println(name) 
    } 
} 

在上述情況下,數據源不被讀取並且具有空值。 是否有任何示例代碼可用於此要求。

我在這裏錯過了什麼嗎?

編輯:

我的Datasources.groovy條目如下。

datasources = { 

    datasource(name:'ds2') { 
     domainClasses([com.Tune]) 
     readOnly(true) 
     driverClassName('oracle.jdbc.driver.OracleDriver') 
     url('jdbc:oracle:thin:@test-ofr.wellmanage.com:1521:OFRS1')   
     username('test') 
     password('test') 
     environments(['development']) 
     dbCreate('do-not-bother') 
     logSql(true) 
     dialect(org.hibernate.dialect.Oracle10gDialect) 
     hibernate { 
      cache { 
       use_second_level_cache(false) 
       use_query_cache(false) 
      } 
     } 
    } 
} 

回答

5

次要數據源都可以使用依賴注入,但他們的名字是基於Datasources.groovy名稱。例如,如果你定義一個名爲「富」數據源,那麼你會注入與def dataSource_foo

class MyController { 

    def dataSource_foo 

    def list = { 
     String nameSql = "select name from emp where id=3345" 
     Sql sql = new Sql(dataSource_foo) 
     def rows = sql.rows(nameSql) 
     ... 
    } 
} 

請注意,您必須把def dataSource_foo爲一類範圍的領域,而不是你的行動(或方法)內。對於每個依賴注入來說都是如此 - 如果它在一個方法或一個閉包內,它只是一個方法範圍變量。

+0

明白了您的觀點,根據您的建議編輯我的代碼,請檢查我的編輯代碼。我的數據源名稱是ds2。所以現在我定義了我的數據源爲def dataSource_ds2。其他選項def ds2仍然得到相同的錯誤「必須指定非空連接」我錯過了什麼? – MAlex 2010-11-12 05:06:57

+0

你是否認爲我的數據寫入方式存在一些問題來源 – MAlex 2010-11-12 08:08:39

+0

@ Burt:感謝您的幫助。這個答案和你的真棒插件當然值得投票 – MAlex 2010-11-12 13:48:41

0

我在最後一個項目的BootStrap中做過這件事。請記住,有效的Java代碼也是有效的Groovy(大部分),並且您不必執行「Grails方式」。只需以您熟悉的方式連接到「from」數據庫,並通過Grails域對象操作將內容存儲在Grails數據源中。示例代碼:

try { 
    Connection con = DriverManager.getConnection ("jdbc:xxxx", "username", "password") 
    ResultSet resultSet = con.createStatement().executeQuery("SELECT * FROM the_table") 
    while(resultSet.next()) { 
     DomainObject domainObjectInstance = new DomainObject(attributeA: resultSet.getString('attributeA'), attributeB: resultSet.getString('attributeB')) 
     if (!domainObjectInstance.save(flush: true)) { 
      println "Unable to save DomainObject: ${domainObjectInstance.errors}" 
     } 
    } 
} catch (SQLException e) { 
    e.printStackTrace(); 
} 
+0

感謝埃裏克最佳實踐。我明白你的觀點。但要求嚴格地說「做它在GRAILS」:( – MAlex 2010-11-12 12:15:00

0

我更新了我的dataSource以下,它工作。我不確定它背後的推理是什麼。

datasources = { 

    datasource(name:'ds2') { 
     domainClasses([com.Tune]) 
     readOnly(true) 
     driverClassName('oracle.jdbc.driver.OracleDriver') 
     url('jdbc:oracle:thin:@test-ofr.tnic.com:1521:OFRS1')   
     username('test') 
     password('test') 
     environments(['development']) 
     dbCreate('do-not-bother') 
     logSql(true) 
     dialect(org.hibernate.dialect.Oracle10gDialect) 
     hibernate { 
      cache { 
       provider_class('net.sf.ehcache.hibernate.EhCacheProvider') 
       use_second_level_cache(true) 
       use_query_cache(true) 
      } 
     } 
    } 
} 
2

只是爲了更新這個問題的答案(我剛拿到一個需要使用兩個不同的mysql數據庫的新項目)。我不得不升級到grails 2.0(是的,我從懶惰升級到1.3.7),因爲它支持多個數據源(不需要使用插件)。

Grails 2.0 - multiple datasources

從例子中,你只需要設置DBS在DataSource.groovy文件

environments { 
development { 
    dataSource { 
     dbCreate = "create-drop" 
     url = "jdbc:h2:mem:devDb" 
    } 
    dataSource_lookup { 
     dialect = org.hibernate.dialect.MySQLInnoDBDialect 
     driverClassName = 'com.mysql.jdbc.Driver' 
     username = 'lookup' 
     password = 'secret' 
     url = 'jdbc:mysql://localhost/lookup' 
     dbCreate = 'update' 
    } 
} 
在域類

然後,指定數據源:

class ZipCode { 

    String code 

    static mapping = { datasource 'lookup' } 
} 
+0

完全相同的代碼不適合我(唯一的區別是我使用的是postgres)我運行dbm-gorm-diff來創建遷移,但是在那裏在構建表的過程中沒有代碼,你能確認這段代碼對你有效嗎?你能夠生成並運行遷移? – 2015-07-07 07:19:08

+0

它不適用於g軌2.4.4與標準查詢,與動態發現者一起工作。使用條件查詢,我必須像Domain.lookup.createCriteria一樣執行此操作 - 即使該域配置爲使用查找數據源。 – 2016-02-02 05:47:59

-1

在Grails Services with SQL中如何使用多個數據源的例子。

提示:您可以使用TestServiceWithInjectionTestService。兩者都很好。

DataSource.groovy中

dataSource { 
    pooled = true 
    jmxExport = true 
    driverClassName = "com.mysql.jdbc.Driver" 
    dialect = "org.hibernate.dialect.MySQL5InnoDBDialect" 
} 
hibernate { 
    cache.use_second_level_cache = true 
    cache.use_query_cache = false 
// cache.region.factory_class = 'org.hibernate.cache.SingletonEhCacheRegionFactory' // Hibernate 3 
    cache.region.factory_class = 'org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory' // Hibernate 4 
    singleSession = true // configure OSIV singleSession mode 
    flush.mode = 'manual' // OSIV session flush mode outside of transactional context 
} 

// environment specific settings 
environments { 
    development { 
     dataSource { 
      dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', '' 
      url = "jdbc:mysql://localhost:3306/database1" 
      username = "root" 
      password = "password" 
     } 
     dataSource_second { 
      driverClassName = "com.mysql.jdbc.Driver" 
      dialect = "org.hibernate.dialect.MySQL5InnoDBDialect" 
      dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', '' 
      url = "jdbc:mysql://localhost:3306/database2" 
      username = "root" 
      password = "password" 
     } 
    } 
    test { 
     dataSource { 
      //Used by local test run (grails test-app) 
      dbCreate = "create-drop" // one of 'create', 'create-drop', 'update', 'validate', '' 
      url = "jdbc:mysql://test-server.com:3306/test_ci" 
      username = "root" 
      password = "password" 
     } 
    } 
} 

TestServiceWithInjection.groovy

package com.github.biniama 

import grails.transaction.Transactional 
import groovy.sql.Sql 

import javax.annotation.PostConstruct 

@Transactional 
class TestService { 

    def dataSource_second 

    Sql sql 

    @PostConstruct 
    def initSql() { 
     sql = new Sql(dataSource_second) 
    } 

    def getData() { 
     def q = "SELECT id FROM job LIMIT 1" 
     return sql.rows(q) 
    } 
} 

TestService.groovy

package com.github.biniama 

import grails.transaction.Transactional 
import groovy.sql.Sql 

@Transactional 
class TestService { 

private Sql sql 

void setDataSource_second(def dataSource) { 
    sql = new Sql(dataSource) 
} 

Integer getData() { 
    def q = "SELECT id FROM job LIMIT 1" 
    return sql.rows(q) 
} 

}

TestController.groovy

package com.github.biniama 

class TestController { 

    TestService testService 

    def index() { 
    Integer result = testService.getData() 
    render "Returned value is ${result}" 
    } 
} 
0

我不知道爲什麼沒有人提到 'C3P0:0.9.1.2:C3P0' 這裏的插件。

這是實現多個數據庫的Grails應用程序

Buildconfig.groovy

compile 'c3p0:c3p0:0.9.1.2' 

數據源

dataSource { 
      dialect = 'com.example.hibernateutil.MySQL5InnoDBDialectBitFixed' 
      dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', '' 
      driverClassName = "com.mysql.jdbc.Driver" 
      url = "jdbc:mysql://127.0.0.1/demo 
      username = "root" 
      password = "" 
     } 

     dataSource_Demo { 
      dialect = 'com.example.hibernateutil.MySQL5InnoDBDialectBitFixed' 
      dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', '' 
      driverClassName = "com.mysql.jdbc.Driver" 
      url = "jdbc:mysql://127.0.0.1/demo2" 
      username = "root" 
      password = "" 
     } 

resources.groovy

beans = { 


    dataSource_Demo(ComboPooledDataSource) { bean -> 
     bean.destroyMethod = 'close' 
     //use grails' datasource configuration for connection user, password, driver and JDBC url 
     user = grailsApplication.config.dataSource_Demo.username 
     password = grailsApplication.config.dataSource_Demo.password 
     driverClass = grailsApplication.config.dataSource_Demo.driverClassName 
     jdbcUrl = grailsApplication.config.dataSource_Demo.url 
     idleConnectionTestPeriod = 2 * 60 * 60 //2 hours 
     testConnectionOnCheckin = true 
    } 

    /** 
    * c3P0 pooled data source that allows 'DB keepalive' queries 
    * to prevent stale/closed DB connections 
    * Still using the JDBC configuration settings from DataSource.groovy 
    * to have easy environment specific setup available 
    */ 
    dataSource(ComboPooledDataSource) { bean -> 
     bean.destroyMethod = 'close' 
     //use grails' datasource configuration for connection user, password, driver and JDBC url 
     user = grailsApplication.config.dataSource.username 
     password = grailsApplication.config.dataSource.password 
     driverClass = grailsApplication.config.dataSource.driverClassName 
     jdbcUrl = grailsApplication.config.dataSource.url 
     idleConnectionTestPeriod = 2 * 60 * 60 //2 hours 
     testConnectionOnCheckin = true 
    } 
} 
相關問題