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/

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值