我們可以通過兩種方式做到這一點:
- 使用格姆(如果他們有一些相同的列)
- 使用查詢
方法1:
創建兩個DataSource.groovy中的數據源。 對於已創建的數據庫,在定義數據源時不要提供dbcreate選項。這將防止何時創建客戶對象,它只會在Test1數據庫中創建記錄。 這兩個數據庫都有客戶表。所以我們可以使用GORM訪問數據。爲此,必須在域中定義數據源「ALL」。
Test1的客戶表包含姓名和年齡欄 Test2的客戶表包含姓名,電子郵件和電話。
通過GORM,我們只能訪問域屬性。所以我只能從Test2的客戶表訪問名字。
在DataSource.groovy中,
dataSource {
pooled = true
driverClassName = "com.mysql.jdbc.Driver"
username = "admin"
password = "admin"
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = false
cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory' // Hibernate 3
// cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' // Hibernate 4
}
// environment specific settings
environments {
development {
dataSource {
dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
url = "jdbc:mysql://localhost:3306/test1"
}
dataSource_test2 {
driverClassName = 'com.mysql.jdbc.Driver'
username = "admin"
password = "admin"
url = "jdbc:mysql://localhost:3306/test2"
}
}
test {
dataSource {
dbCreate = "update"
url =
"jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
}
}
..........
.......
在Customer.groovy,
class Customer {
static constraints = {
}
String name
int age
static mapping = {
datasource 'ALL'
}
}
在控制器,
class CustomerController {
def dataSource_test2
def testingDB(){
Customer.test2.list().each{
println it.name
}
println Customer.list()
render "hi"
}
}
方式2:
class MainController {
def dataSource_test2
def index() {
String nameSql = "select * from customer"
Sql sql = new Sql(dataSource_test2)
def rows = sql.rows(nameSql)
println rows
}
}