Skip to content

Documentation appears to be incorrect for joinTable & column in many-to-many mapping #14625

Open
@abryzakez

Description

@abryzakez

The documentation at http://gorm.grails.org/latest/hibernate/manual/index.html#_many_to_many_mapping shows how to change the column name & join table for a many-to-many relationship by creating a mapping in both classes:

class Group {
   ...
   static mapping = {
       people column: 'Group_Person_Id',
              joinTable: 'PERSON_GROUP_ASSOCIATIONS'
   }
}
class Person {
   ...
   static mapping = {
       groups column: 'Group_Group_Id',
              joinTable: 'PERSON_GROUP_ASSOCIATIONS'
   }
}

This documentation seems to show that the column should be the ID of the other class, but it appears that it is the ID of the current class. I created a test to demonstrate this.

class A {
    Long id
    String value

    static hasMany = [
            b: B,
    ]
    static mapping = {
        id generator: 'assigned'
        b column: 'B_ID', joinTable: 'A_B'
    }

    static def allJoins() {
        def result
        withSession { session ->
            def q = session.createSQLQuery("SELECT A_ID, B_ID FROM A_B")
            result = q.list()
        }
        return result
    }
}
class B {
    Long id
    String value

    static belongsTo = A
    static hasMany = [
            a: A,
    ]

    static mapping = {
        id generator: 'assigned'
        a column: 'A_ID', joinTable: 'A_B'
    }
}
import grails.test.mixin.integration.Integration
import grails.transaction.Rollback
import spock.lang.Specification

@Integration
@Rollback
class ABSpec extends Specification {
    void "ab join columns"() {
        given:
        def a1 = new A(value: 'A1')
        a1.id = 101
        a1.save()
        def b1 = new B(value: 'B1')
        b1.id = 201
        b1.save()
        a1.addToB(b1)
        a1.save(flush: true)

        expect:
        A.allJoins() == [[101, 201]]
    }
}

This test fails with the IDs in the incorrect order (the result is [[201,101]])

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions