`

Grails 对于多数据源的增删改查操作

阅读更多

Grails 对于多数据源的增删改查操作

 

多数据源配置成功后,需要在Domain的mapping这种指定要映射的数据库表,可选则映射到所有库,也可指定某一个数据库,方式如下:

 

假设:有两个数据源配置:dataSource和extraSource,相关配置参考:Grails 多数据源相关配置说明

 

Configuring Domain Classes

If a domain class has no DataSource configuration, it defaults to the standard 'dataSource'. Set the datasource property in the mapping block to configure a non-default DataSource. For example, if you want to use the ZipCode domain to use the 'lookup' DataSource, configure it like this:

class ZipCode {

   String code

   static mapping = {
      datasource 'lookup'
   }
}

A domain class can also use two or more data sources. Use the datasources property with a list of names to configure more than one, for example:

class ZipCode {

   String code

   static mapping = {
      datasources(['lookup', 'auditing'])
   }
}

If a domain class uses the default DataSource and one or more others, use the special name 'DEFAULT' to indicate the default DataSource:

class ZipCode {

   String code

   static mapping = {
      datasources(['lookup', 'DEFAULT'])
   }
}

If a domain class uses all configured data sources, use the special value 'ALL':

class ZipCode {

   String code

   static mapping = {
      datasource 'ALL'
   }
}

下面是例子,以两个数据库为例子:

 

Namespaces and GORM Methods

If a domain class uses more than one DataSource then you can use the namespace implied by each DataSource name to make GORM calls for a particular DataSource. For example, consider this class which uses two data sources:

class ZipCode {

   String code

   static mapping = {
      datasources(['lookup', 'auditing'])
   }
}

The first DataSource specified is the default when not using an explicit namespace, so in this case we default to 'lookup'. But you can call GORM methods on the 'auditing' DataSource with the DataSource name, for example:

def zipCode = ZipCode.auditing.get(42)
...
zipCode.auditing.save()

 

 

control和service中获取数据源的方式:

 

1.DataSource dataSource 获取默认数据源

 

2. DataSource dataSource_lookup 获取其他数据源

 

获取数据源之后可直接对数据库进行增删改查操作:

classTestService{
def dataSource_gibmsSource
def insertTest(){
Sql sql =newSql(dataSource_gibmsSource)
def gibmsSql ="insert into test_gibms(code) values ('000')"
def result = sql.executeInsert(gibmsSql)
sql.close()
}
}

 

 

参考文档:http://yongfengsun.blog.163.com/blog/static/792553852016217112851842/

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics