Hibernate学习手记(5)--关联映射

关于Hibernate的关联映射(annotation专版)

举一典型到老掉牙的例子说明:TeacherStudentCourse之间的关系。

TeacherCourse是一对一关系;

StudentCourse是一对多关系;

TeacherStudent是多对多关系;

....................

@Entity

@Table(name="Student")

publicclassStudent{

privateintid;

privateStringname;

privateStringsex;

privateCoursecourse;

privateSet<Teacher>teachers=newHashSet<Teacher>();

//建立Student与Teacher的双向多对多关联

@ManyToMany(mappedBy="students")

publicSet<Teacher>getTeachers(){

returnteachers;

}

publicvoidsetTeachers(Set<Teacher>teachers){

this.teachers=teachers;

}

//单向多对一关联

@ManyToOne

publicCoursegetCourse(){

returncourse;

}

publicvoidsetCourse(Coursecourse){

this.course=course;

}

@Id

@Column(name="s_id")

publicintgetId(){

returnid;

}

@Column(name="s_name")

publicStringgetName(){

returnname;

}

@Column(name="s_sex")

publicStringgetSex(){

returnsex;

}

.............

}

..............................................

@Entity

@Table(name="Teacher")

publicclassTeacher{

privateintid;

privateStringname;

privateStringsex;

privateStringtitle;

privateCoursecourse;

privateSet<Student>students=newHashSet<Student>();

//Teacher与Student的单向多对多联系

@ManyToMany

@JoinTable(name="t_s",

joinColumns={@JoinColumn(name="t_id")},

inverseJoinColumns={@JoinColumn(name="s_id")}

)

//设置多对多关系的中间表,其中joinColumns属性里面指向本实体数据表的关联字段,

//inverseJoinColumns属性则指向中间表的另一关联字段对应的数据表的关联字段

publicSet<Student>getStudents(){

returnstudents;

}

publicvoidsetStudents(Set<Student>students){

this.students=students;

}

//Teacher与Course的一对一关联

@OneToOne

@JoinColumn(name="Course_id")

//JoinColumn,指定Course表的外键

publicCoursegetCourse(){

returncourse;

}

publicvoidsetCourse(Coursecourse){

this.course=course;

}

@Id

@Column(name="t_id")

publicintgetId(){

returnid;

}

@Column(name="t_name")

publicStringgetName(){

returnname;

}

@Column(name="t_sex")

publicStringgetSex(){

returnsex;

}

@Column(name="t_title")

publicStringgetTitle(){

returntitle;

}

..................

}

..........................

@Entity

@Table(name="Course")

publicclassCourse{

privateintid;

privateStringname;

privateStringscore;

privateSet<Student>student=newHashSet<Student>();

privateTeacherteacher;

/*

*为实现双向的一对一关联,添加属性mappedBy,使确定该实体被映射在teacher中的course属性上,主导放在多的一方

**/

@OneToOne(mappedBy="course")

publicTeachergetTeacher(){

returnteacher;

}

publicvoidsetTeacher(Teacherteacher){

this.teacher=teacher;

}

/*

*为实现双向的多对一关联,添加属性mappedBy,使确定该实体被映射在student中的course属性上,主导放在多的一方

**/

@OneToMany(mappedBy="course")

//单向一对多关联

//@JoinColumn(name="Course_id")

publicSet<Student>getStudent(){

returnstudent;

}

publicvoidsetStudent(Set<Student>student){

this.student=student;

}

@; background: #c0c0c0; colo

分享到:
评论

你可能感兴趣的:(Hibernate)