2

我们在 Grails 中创建了两个不同的域对象,并尝试从两个不同的模式进行访问。

方法一:

例如:

学生.groovy

class Students {
     String id
     String name
     String address 

   Static mapping = {
     schema: 'student_details' 
   } 
 }

客户.groovy

class Customer {
    String firstName
    String lastName 
    String address  

   Static mapping = {
      schema: 'customer_details'
    }    
 }

应用程序.yml

 environments:
    development:
       dataSource:
          dbCreate: update
          url: jdbc:mysql://localhost:3306/

如果我在 url 连接字符串中提供默认架构,它总是引用该默认架构,而不管域类中定义的架构并抛出异常,找不到表。如果我从 url 连接字符串中删除默认架构,我会在日志中收到“未选择数据库”错误。

方法二:

我们尝试在application.yml中为每个模式配置多个数据源选项,如下所示:

dataSource:
    pooled: true
    dbCreate: update
    url: jdbc:mysql://localhost:3306/sample_grails
    dialect: org.hibernate.dialect.MySQL5InnoDBDialect
    username: root
    password: ''
secondary:
    pooled: true
    dbCreate: update
    url: jdbc:mysql://localhost:3306/grails_mapping
    dialect: org.hibernate.dialect.MySQL5InnoDBDialect
    username: root
    password: ''

使用域类作为Customer.groovy

class Customer {
    String firstName
    String lastName 
    String address  

   Static mapping = {
      datasource 'secondary'
   }     
 }

我收到一个错误

Caused by: org.grails.datastore.mapping.core.exceptions.ConfigurationException: DataSource not found for name [secondary] in configuration. Please check your multiple data sources configuration and try again.

我们参考了以下链接以进行多模式访问:

https://objectpartners.com/2016/03/09/using-secondary-datasources-in-grails-3/

在 Grails 中使用模式创建域类

任何人都可以提出解决方案吗?

4

2 回答 2

1

您的方法 2 几乎就在那里,我认为您缺少的是-您需要在“数据源”下定义“辅助”-请参阅此-http: //docs.grails.org/latest/guide/conf.html#multipleDatasources

于 2017-10-28T13:19:54.027 回答
0

在你的 application.yml 文件中,使用datasources:在你的默认数据源下面这样:

dataSource:
   pooled: true
   dialect: org.hibernate.dialect.MySQL5InnoDBDialect
   driverClassName: com.mysql.jdbc.Driver
   dbCreate: update
   url: jdbc:mysql://localhost:3306/default_schema
   username: root
   password: ''
datasources:
  source1:
    dialect: org.hibernate.dialect.MySQLInnoDBDialect
    driverClassName: com.mysql.jdbc.Driver
    username: root
    password: ''
    url: mysql://localhost:3306/source1
    dbCreate: update

现在,您的 Customer 类应该看起来像

class Customer {
String firstName
String lastName 
String address
Static mapping = {
  datasource 'source1'
}     
}

更多详细信息,您可以查看Multiple Datasources In Grails,官方文档

于 2017-10-27T16:42:36.303 回答