Пример использования нескольких источников данных в Grails Services с 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}"
}
}