2013-07-16 130 views
0

我在我們的數據庫中有兩個需要映射的表。首先是學生表。它看起來是這樣的:在Grails中映射兩個領域類

id 
first_name 
last_name 
major_code_1 
major_code_2 

而且主要表是這樣的:

id 
description 

我需要映射的學生,主要的代碼,其中major_code_1major_code_2點到id在主要表格。我怎麼能這樣做?謝謝!

回答

0

的代碼可以像(一個一對多的關係:主要可以有很多學生):

class Student{ 

    Long id 
    String first_name 
    String last_name 

    static belongsTo = [ 
      major_code_1: Major 
      , major_code_2: Major 
    ] 

    static mapping = { 
     table 'Student' 
    } 

} 


class Major{ 

    Long id 
    String description 

    static hasMany = [ 
     student_1: Student 
     , student_2: Student 
    ] 

    static mappedBy = [ 
      student_1: 'major_code_1' 
      , student_2: 'major_code_2' 
    ] 

    static mapping = { 
     table 'Major' 
    } 

} 

但你能解釋一下我這兩個表的想法。因爲它看起來像被稱爲學生的主要實體之間多對多的遞歸關係。我想知道你是否應該在主表中沒有student_code_1和student_code_2。

--------------------------------編輯------------- -----------------------------------

與多對一的關係(許多學生有同一專業)

class Student{ 

    Long id 
    String first_name 
    String last_name 

    Major major_code_1 
    Major major_code_2 

    static mapping = { 
     table 'Student' 
    } 

} 


class Major{ 

    Long id 
    String description 

    static belongsTo = [ 
     student_1: Student 
     , student_2: Student 
    ] 

    static mappedBy = [ 
      student_1: 'major_code_1' 
      , student_2: 'major_code_2' 
    ] 

    static mapping = { 
     table 'Major' 
    } 

} 
+0

基本上學生對象可以有兩個專業... major1,major2。在數據庫中,學員中的major_code_1和major_code_2只是一個指向Major表的代碼。從那裏你可以得到主要描述(計算機信息科學,經濟學等) 作爲一所大學,這是一個遺留數據庫,所以如果它不能很好地映射到Grails域類,那就是原因。 – grantmcconnaughey

+0

現在我明白了。所以我的答案代碼應該可以正常工作。你只能添加一個約束是學生類,以避免一個學生有兩個相同的專業。 – kpater87

+0

如果學生在自己身邊,這需要改變一點嗎? – grantmcconnaughey

3

下面是一個簡單的模型映射到您的模式:

class Student { 
    String firstName 
    String lastName 
    Major firstMajor 
    Major secondMajor 

    static mapping = { 
     table 'Student' 
     firstMajor column: 'major_code_1' 
     secondMajor column: 'major_code_2' 
    } 
} 

class Major { 
    String description 

    static mapping = { 
     table 'Major' 
    } 
} 

因爲你在沒有指定級聯行爲,我已經離開了所有belongsTo及其他經濟領域的問題1上。

+0

+1。 *簡單是最終的複雜性。* – dmahapatro