1. 程式人生 > >1.21 多對多關係 (單向)

1.21 多對多關係 (單向)

例如:老師與學生的關係,一個老師對應多個學生,一個學生對應多個老師。多對多的關係就是在teacher表和student表中間加入了一箇中間表,用來對映關係。


需要說明:teacher知道有多少個學生,而學生不知道有多少個老師(即在teacher類中加入student的集合set)才叫單向。

一、annotation方式

1.teacher類

@Entity
public class Teacher {
private int id;
private String name;
private Set<Student> students = new HashSet<Student>();


@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToMany                                                                         ‘指明多對多的關係
@JoinTable(name="t_s",
joinColumns={@JoinColumn(name="teacher_id")},              ’指明teacher表中對映的欄位,也可能多個欄位
inverseJoinColumns={@JoinColumn(name="student_id")}  ‘指明對應student表中對映的欄位,可能多欄位
)

public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
}

2.student類

@Entity
public class Student {
private int id;
private String name;

@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}


3.hibernate.cfg.xml

<mapping class="com.bjsxt.hibernate.Teacher"/>
<mapping class="com.bjsxt.hibernate.Student"/>

二、xml方式

1.teacher的xml配置

<hibernate-mapping>
<class name="com.bjsxt.hibernate.Teacher">
<id name="id">
<generator class="native"></generator>
</id>

<property name="name"></property>
<set name="students" table="t_s">
<key column="teacher_id"></key>
<many-to-many class="com.bjsxt.hibernate.Student" column="student_id"/>
</set>

    </class>

</hibernate-mapping>

2.student的xml配置方式

<hibernate-mapping>
<class name="com.bjsxt.hibernate.Student">
<id name="id">
<generator class="native"></generator>
</id>

<property name="name"></property>
    </class>

</hibernate-mapping>

3.hibernate.cfg.xml配置

<mapping resource="com/bjsxt/hibernate/Teacher.hbm.xml"/>
<mapping resource="com/bjsxt/hibernate/Student.hbm.xml"/>