举个栗子
教师(teacher)与课程(course)之间的关系
一个教师可以上多门课程(one-to-many),同一课程只能由一个老师上课。
数据库表结构:
teacher(t_id,t_name);
course(c_id,c_name,t_id);
JavaBean
Course的映射文件
<hibernate-mapping package=”beans”>
<class name = “Course” table=”course”>
<id name = “cid” column=”c_id”>
<generator class=”assigned” />
</id>
<property name=”cname” column=”c_name”></property>
<set name=”studentSet” table=”score” inverse=”true” cascade=”save-update” >
<key column=”c_id”></key>
<many-to-many class=”Student” column=”s_id”></many-to-many>
</set>
<!– 多个课程对应一个老师 –>
<
many-to-one
name=”teacher” column=”t_id”></many-to-one>
</class>
</hibernate-mapping>
<hibernate-mapping package=”beans”>
<class name = “Teacher” table=”teacher”>
<id name = “tid” column=”t_id”>
<generator class=”assigned” />
</id>
<property name=”tname” column=”t_name”></property>
<!– 一个老师对应多个课程 通过t-id这一列来连接表–>
<set name=”courseSet” inverse=”true” cascade=”save-update”>
<key column=”t_id”></key>
<
one-to-many class=”Course”
/>
</set>
</class>
</hibernate-mapping>
测试:查询老师表,并且查询每个老师对对应的课程:
结果: