我试图在另一个问题中提出这个问题,但是我可能提出了太多细节。
我正在使用Grails和多个数据源。
如果您想使用服务来声明数据源,那对我根本不起作用。
static datasource = "db1"
无论如何,这在Grails Services中对我不起作用
感谢您的帮助/建议。
==
我正在编辑它以包括我的Datasource.groovy
现在,如果我在第二个数据库的域对象上使用静态映射,则可以正常工作。但是,我希望服务决定必须将哪个数据库写入其中,因此我希望服务datasource属性的作用与文档中的相同。
静态数据源=“db21”
==============编辑==============
dataSource {
pooled = true
driverClassName = "org.h2.Driver"
username = "sa"
password = ""
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = true
cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
}
// environment specific settings
environments {
development {
dataSource {
dbCreate = "validate"
url = "jdbc:h2:devDb;MVCC=TRUE"
}
dataSource_db1 {
dbCreate = "validate"
url = "jdbc:h2:dev1Db;MVCC=TRUE"
pooled = true
driverClassName = "org.h2.Driver"
username = "sa"
password = ""
}
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:h2:mem:testDb;MVCC=TRUE"
}
}
production {
dataSource {
dbCreate = "update"
url = "jdbc:h2:prodDb;MVCC=TRUE"
pooled = true
properties {
maxActive = -1
minEvictableIdleTimeMillis=1800000
timeBetweenEvictionRunsMillis=1800000
numTestsPerEvictionRun=3
testOnBorrow=true
testWhileIdle=true
testOnReturn=true
validationQuery="SELECT 1"
}
}
}
}
最佳答案
我们在Grails应用程序中使用了多个数据源,并已成功使用您上面指定的方法在Service中切换了数据源...
static datasource = "db1"
但是,不同之处在于,在我们所有的域对象中,我们都定义了该域对象所属的数据源。我不确定如果不在映射中定义非默认数据源是否可以做。
static mapping = { datasource 'db1' }
在某些情况下,我们将拥有两个具有相同名称但指向不同数据源的不同域类。为了保持这种状态,我们将2个域类放在不同的程序包中,并将使用这些域类/数据源的服务放在同一程序包中。
例如...
//Domain Classes
package com.yourcompany
class Student {
static mapping = {
//if you don't indicate the datasource it will use the default
}
}
package com.yourcompany.db1
class Student {
static mapping = {
datasource 'db1'
}
}
//Services
package com.yourcompany
class DefaultDbService {
def getStudents() {
//This will query the default datasource
Student.findAll()
}
}
package com.yourcompany.db1
class Db1Service {
static datasource = "db1"
def getStudents() {
//This will query the 'db1' datasource
Student.findAll()
}
}
您可以尝试这种方法,看看是否能获得所需的结果。