问题
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