在Grails Services with SQL中如何使用多個數據源的例子。
提示:您可以使用TestServiceWithInjection
或TestService
。兩者都很好。
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}"
}
}
明白了您的觀點,根據您的建議編輯我的代碼,請檢查我的編輯代碼。我的數據源名稱是ds2。所以現在我定義了我的數據源爲def dataSource_ds2。其他選項def ds2仍然得到相同的錯誤「必須指定非空連接」我錯過了什麼? – MAlex 2010-11-12 05:06:57
你是否認爲我的數據寫入方式存在一些問題來源 – MAlex 2010-11-12 08:08:39
@ Burt:感謝您的幫助。這個答案和你的真棒插件當然值得投票 – MAlex 2010-11-12 13:48:41