跨两个数据源的 Grails GORM 域关联 [英] Grails GORM domain association across two datasources
问题描述
如果另一个域类使用不同的数据源,是否可以在两个域类(即 belongsTo
)之间建立关联?这两个数据源也是不同的数据库驱动程序.
Is it possible to have an association between two domain classes (i.e. belongsTo
) if the other domain class uses a different datasource? The two datasources are different database drivers too.
我怀疑这可能是不可能的,但我想联系这里的社区,看看是否可能.现在我正在尝试这样做,但我收到了通常怀疑的休眠错误:
I suspect this may not be possible, but I wanted to reach out to the community here to see if it was possible. Right now I'm trying to do it and I am getting the usual suspected Hibernate error:
调用init方法失败;嵌套异常是 org.hibernate.MappingException:来自表 domain_class_A 的关联引用了未映射的类:DomainClassB
示例:
class DomainClassA {
static belongsTo = [dcB: DomainClassB]
static mapping = {
datasource "ds1"
table name: "domain_class_A", schema: "schema_A"
}
}
class DomainClassB {
static hasMany = [dcA: DomainClassA]
static mapping = {
datasource "ds2"
table name: "domain_class_B", schema: "schema_B"
}
}
推荐答案
正如@dmahapatro 在他的评论中指出的,这类似于 1-element 的情况,创建自己的方法来管理关系是要走的路.这也与我不久前关于映射集合的性能问题的一次演讲有关,因此您可以一石激起二只:http://www.infoq.com/presentations/GORM-Performance
As @dmahapatro points out in his comment, this is similar to the 1-element case, and creating your own methods to manage the relationship is the way to go. This is also related to a talk I did a while back about performance issues with mapped collections, so you can kill two birds with one stone: http://www.infoq.com/presentations/GORM-Performance
如果您不需要集合,即如果您只使用它来添加子对象的新实例,那么这将起作用,因为 get
调用 DomainClassB
实例将使用其数据源:
If you don't need the collection, i.e. if you only use it to add new instances of the child object, then this will work because the get
call for the DomainClassB
instance will use its datasource:
class DomainClassA {
Long domainClassBId
private DomainClassB dcB
DomainClassB getDomainClassB() {
if (!dcB && domainClassBId) {
dcB = DomainClassB.get(domainClassBId)
}
dcB
}
void setDomainClassB(DomainClassB dc) {
domainClassBId = dc.id
}
static transients = ['domainClassB']
static mapping = {
datasource "ds1"
table name: "domain_class_A", schema: "schema_A"
}
}
class DomainClassB {
static mapping = {
datasource "ds2"
table name: "domain_class_B", schema: "schema_B"
}
}
创建一个新的 DomainClassA 实例与传统的 addTo...
方法有点不同,但还不错:
Creating a new DomainClassA instance is a bit different from the traditional addTo...
approach, but it's not too bad:
DomainClassB dcb = ...
def dca = new DomainClassA(domainClassBId: dcb.id)
dca.save()
如果您确实希望访问 DomainClassB
的所有 DomainClassA
实例,您可以为此添加一个方法:
If you do want access to all of the DomainClassA
instances for a DomainClassB
, you can add a method for that:
Set getDomainClassAs() {
DomainClassA.findAllByDomainClassBId(id)
}
但是由于您自己进行查询,因此如果您只需要一些实例,则不必加载所有实例,因此您可以执行任何您想做的查询.
But since you're doing the query yourself, you don't have to load all of the instances if you only need some, so you can do whatever queries you want.
这篇关于跨两个数据源的 Grails GORM 域关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!