简体   繁体   English

Grails如何与SQL Server数据库正确地一对多映射

[英]Grails How to Correctly Map One-to-Many with a SQL Server database

I have two domain classes and the relationship between them is 1 to Many. 我有两个域类,它们之间的关系是一对多。 I know how to map the columns of each class to their respective tables individually but how do I map the relationship that exists in my MSSQL database? 我知道如何将每个类的列分别映射到各自的表,但是如何映射MSSQL数据库中存在的关系? There is no join table and I only have read-only access. 没有联接表,我只有只读访问权限。 I've looked at various pages of the Grails documentation and this is where I am at at the moment (One student has many courses). 我浏览了Grails文档的各个页面,这就是我目前的位置(一个学生有很多课程)。 In my tables the foreign key that ties the two tables together is in the Courses table. 在我的表中,将两个表联系在一起的外键在“课程”表中。

class StudentHeader { //on the one side
    String stuNo
    String stuName
    String stuStreet

    static mappedBy = [refs: "fkCustNo"]

    static hasMany = [refs: CourseHeader]
    static constraints = {
    }

    static mapping = {
        table name: "[tbl_Students]", schema: "[dbo]", catalog: "[CRD].[CourseTrak]"
        version false
        id generator: 'assigned', name: 'stuNo'
        stuNo column: '[PK_StudentNo]'
        stuName column: '[Student_Name]'
        stuStreet column: '[Student_Street]'


    }
}

class CourseHeader { //on the many side
    String courId
    String courName
    StudentHeader fkCourNo
    static constraints = {
    }

    static mapping = {
        table name: "[tbl_Courses]", schema: "[dbo]", catalog: "[CRD].[CourseTrak]"
        version false
        id generator: 'assigned', name: 'courId'
        courId column: '[PK_CourseId]'
        courName column: '[Course_Name]'
        fkCourNo column: '[FK_CourseNo]'


    }
}

As a test here is how I am trying to access the courses of a student 作为测试,这是我尝试访问学生课程的方式

StudentHeader.first().refs

I believe I have it figured out. 我相信我已经解决了。 For the domain class on the many side you need to set insert and updateable equal to false like so (The object field in your "many" domain has to have the same value as the key-value pair in mappedBy): 对于许多方面的域类,您需要将insert和updateable设置为false,如下所示(“许多”域中的对象字段必须具有与appedBy中的键值对相同​​的值):

class StudentHeader{
static mappedBy = [refs: "fkCustNo"]
}

class CourseHeader { //on the many side
    String courId
    String courName
    StudentHeader fkCustNo
    static constraints = {
    }

    static mapping = {
        table name: "[tbl_Courses]", schema: "[dbo]", catalog: "[CRD].[CourseTrak]"
        version false
        id generator: 'assigned', name: 'courId'
        courId column: '[PK_CourseId]'
        courName column: '[Course_Name]'
        fkCustNo column: '[FK_CourseNo]', insertable: false, updateable: false


    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM