一个 Grails 域中的多个多对多关联 class

Multiple many-to-many associations in one Grails domain class

我正在使用 Grails 3.0.6,并且正在努力处理复杂且高度互连的域模型。我有 classes 与其他 classes 有多个多对多关联,我别无选择,只能在至少一个 class 上有多个 belongsTo 关联。我无法弄清楚表示它的语法。

我的域模型非常复杂,但我能够将我的问题简化为这个简化的示例:

class Graph {
    static hasMany = [vertices: Vertex]
}

class OtherClass {
    static hasMany = [vertices: Vertex]
}

class Vertex {
    static hasMany = [graph: Graph, other: OtherClass]
}

在这个简化的示例中,我可以通过在 Graph 和 OtherClass 上的域 classes 之间声明所有权来解决这个问题...在我复杂的域模型中,我没有这个选择,因为有太多 class 具有多个多对多关联。

我试过这个:

class Vertex {
    static hasMany = [graphs: Graph, others: OtherClass]
    static belongsTo = Graph, OtherClass
}

但我得到了 NPE。

我试过这个:

class Vertex {
    static hasMany = [graphs: Graph, others: OtherClass]
    static belongsTo = [graphs: Graph, others: OtherClass]
}

但我仍然得到 "GrailsDomainException: No owner defined between domain classes [Graph] and [Vertex]"

我可以用 mappedBy 做些什么来正确表示这个吗?

在我的许多多对多关联中,实际上并不需要级联保存(尽管它们不会造成伤害),因此我不需要为此目的使用 belongsTo(或 "owner") .这让我想知道域 classes 上的关联是否真的是我应该如何建模这些关系。还有什么我可以做的吗?

根据 Burt Beckwith 的评论,我创建了一个额外的域 class 来表示连接 table。现在,一个多对多的关联分解为两个一对多的关联,问题就不会出现了。

示例:

class Graph {
    static hasMany = [graphVertexRelations: GraphVertexRelation]
}

class OtherClass {
    static hasMany = [vertices: Vertex]
}

class Vertex {
    static hasMany = [graphVertexRelations: GraphVertexRelation, others: OtherClass]
    static belongsTo = OtherClass
}

class GraphVertexRelation {
    static belongsTo = [graph: Graph, vertex: Vertex]

    static GraphVertexRelation create(Graph graph, Vertex vertex, boolean flush = false) {
        new GraphVertexRelation(graph: graph, vertex: vertex).save(flush: flush, insert: true)
    }
}

您看到的异常 "GrailsDomainException: No owner defined between domain classes [Graph] and [Vertex]" 意味着 ORM 无法弄清楚基 class 是什么,并且 Graph 和 Vertex 之间存在循环关系。

如果您想维护关系以查看顶点所在的图形,您可以使用条件进行反向查找。

class Graph {
    static hasMany = [vertices: Vertex]
}

class OtherClass {
    static hasMany = [vertices: Vertex]
}

class Vertex {
    static transients = ['graphs']
    static hasMany = [other: OtherClass]

    List<Graph> getGraphs() {
        // Backwards link, using the graph table
        Graph.withCriteria() {
            vertices {
                inList("id", [this.id.toLong()])
            }
        }
    }
}