在實際開發中,多對多雙向表會盡量避免而無法完全避免,一旦遇到這個情況時hibernate的映射方法如下
舉個例子:
多對多雙向關聯
關系舉例:老師<-->學生,老師需要知道自己教了哪些學生,學生也知道自己有哪些老師.
數據庫:中間表
Annotation:@ManyToMany
XML:<many-to-many>
多對多單向配置只需要在一端進行配置就可以了,雙向需要配置兩端.
關系模型(Teache多對多Student)
Teacher(id,name,students)多
Set<Student> students=new HashSet<Student>()
Student(id,name,teachers)多
Set<Teacher> teachers = new HashSet<Teacher>();
Annotation配置
在Teacher這一端的students上配置
//如果手動指定生成的中間表的表名和字段名
@ManyToMany
@JoinTable(name="t_s",
joinColumns={@JoinColumn(name="teacher_id")},
inverseJoinColumns={@JoinColumn(name="student_id")}
)
在Student一端的teachers只需要配置
@ManyToMany(mappedBy="students")
XML配置方式:兩端配置一樣,注意表名和生成的中間表的字段屬性名要一致
Teacher那一端配置
<set name="students" table="t_s">
<key column="teacher_id"/>
<many-to-many class="com.xxx.Student" column="student_id"/>
</set>
在Student那一端配置
<set name="teachers" table="t_s">
<key column="student_id"></key>
<many-to-many class="com.xxx.Teacher" column="teacher_id"/>
</set>
生成的表為
create table Student (
id integer not null auto_increment,
name varchar(255),
primary key (id)
)
create table Teacher (
id integer not null auto_increment,
name varchar(255),
primary key (id)
)
create table t_s (//生成的中間表
teacher_id integer not null,
student_id integer not null,
primary key (teacher_id, student_id)
)
t_s表的兩個屬性分別references其它表的主鍵.
t_s(teacher_id, student_id)為中間表,ID策略為聯合主鍵
@orderby(value="id")
posted on 2011-04-19 19:52
林齊磊花 閱讀(1369)
評論(0) 編輯 收藏