无法在 Grail & Groovy 中自定义域类的架构



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

方法1:

例如:

Student.groovy

class Students {
String id
String name
String address 
Static mapping = {
schema: 'student_details' 
} 
}

Customer.groovy

class Customer {
String firstName
String lastName 
String address  
Static mapping = {
schema: 'customer_details'
}    
}

application.yml

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

如果我在url连接字符串中提供了一个默认模式,它总是引用该默认模式,而不管域类和抛出异常中定义的模式如何,都找不到表。如果我从url连接字符串中删除默认架构,则日志中会出现"未选择数据库">错误。

方法2:

我们尝试在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 中创建具有模式的域类

有人能提出解决方案吗?

您的方法2就快到了,我认为您缺少的是-您需要在"datasources"下定义"secondary"-请参阅-http://docs.grails.org/latest/guide/conf.html#multipleDatasources

在application.yml文件中,使用默认数据源下方的数据源:

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

现在,你的客户类应该看起来像

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

有关更多详细信息,您可以参阅Grails中的多个数据源,官方文档

最新更新