Mapping two domain classes in Grails

随声附和 提交于 2019-12-10 11:49:20

问题


I have two tables in our database that need mapped. The first is a Student table. It looks something like this:

id
first_name
last_name
major_code_1
major_code_2

And the Major table is like this:

id
description

I need to map the major codes of the student, where major_code_1 and major_code_2 point to an id in the Major table. How could I do this? Thanks!


回答1:


Here is a simple model which maps to your schema:

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

I've left out all belongsTo and other ownership fields as you didn't specify cascade behavior in your question.




回答2:


The code can look like (with one-to-many relations: Major can have many Students):

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

}

But could you please explain me the idea of this two tables. Because it looks like recursive relationship many to many between Major Entity which is called Student. I wonder if you shouldn't have student_code_1 and student_code_2 in the Major table.

-------------------------------- EDIT ------------------------------------------------

With many-to-one relation (Many Students have the same Major)

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

}


来源:https://stackoverflow.com/questions/17677406/mapping-two-domain-classes-in-grails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!