簡體   English   中英

Grails如何與SQL Server數據庫正確地一對多映射

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

我有兩個域類,它們之間的關系是一對多。 我知道如何將每個類的列分別映射到各自的表,但是如何映射MSSQL數據庫中存在的關系? 沒有聯接表,我只有只讀訪問權限。 我瀏覽了Grails文檔的各個頁面,這就是我目前的位置(一個學生有很多課程)。 在我的表中,將兩個表聯系在一起的外鍵在“課程”表中。

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]'


    }
}

作為測試,這是我嘗試訪問學生課程的方式

StudentHeader.first().refs

我相信我已經解決了。 對於許多方面的域類,您需要將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