一对多/多对一关联
Class member()
{
Int memberid;
String membername;
Team team;
}
<hibernate-mapping> <class name="com.suxiaolei.hibernate.pojos.Member " table="member "> <id name="id" type="string"> <column name="id"></column> <generator class="uuid"></generator> </id> <property name="membername " column=" membername " type="string"></property> <many-to-one name="team " class="com.suxiaolei.hibernate.pojos.Team " column="team _id" –外键列名。
cascade="save-update"> </many-to-one> </class> </hibernate-mapping>
Class Team()
{
Int teamid;
String teamname;
Set<Member>members;
}
<hibernate-mapping>
<class name="com.suxiaolei.hibernate.pojos.Team " table="team ">
<!-- 主键设置 -->
<id name="id" type="string">
<columnname="id"></column>
<generatorclass="uuid"></generator>
</id>
<!-- 属性设置 -->
<propertyname="teamname" column="teamname" type="string"></property>
<set name="members" inverse="true" cascade="all"> <!--设置inverse=”true”表示由多方来维持关联关系,这样在持久化的时候能保证多方主动获取单方的主键值来作为自己的外键值。 在one-to-manay关联关系中,一般将manay端设置为主控方, 这样将有助于改善性能。默认情况下inverse=”false” -->
<key column="team _id" ></key> --关联表的外键列名。
<one-to-many class="com.suxiaolei.hibernate.pojos.Member "/>
</set>
</class>
</hibernate-mapping>
安装上述配置以后,在代码中就可以使用hibernate以面向对象的方式来操作实体对象了,他们之间的关系将由hibernate为我们主动维护,我们只需要获取相关的信息就可以了。
例如:
Student stu = new Student();
stu.setSno("2008002");
stu.setSname("shirdrn");
Teacher t = new Teacher();
t.setTname("王老师");
stu.setTeacher(t);
session.save(stu);
一些级联删除和级联更新的内容大家自己去了解。

多对多关联
Class student()
{
Int studentid;
String studentname;
Set<Course> courses;
}
<hibernate-mapping> <class name="com.suxiaolei.hibernate.pojos.Student" table="student"> <id name="id" type="integer"> <column name="id"></column> <generator class="increment"></generator> </id> <property name="name" column="name" type="string"></property> <set name="courses" inverse="false" cascade="save-update" table="student_course">--中间表名称 <key column="student_id"></key>--己方实体类的主键属性对应的中间表列名称 <many-to-many class="com.suxiaolei.hibernate.pojos.Course" column="course_id"></many-to-many>--对方实体类及其主键属性对应的中间表列名称 </set> </class> </hibernate-mapping>
Class Course()
{
Int courseid;
String courseName;
Set<Student>students;
}
<hibernate-mapping> <class name="com.suxiaolei.hibernate.pojos.Course" table="course"> <id name="id" type="integer"> <column name="id"></column> <generator class="increment"></generator> </id> <property name="name" column="name" type="string"></property> <set name="students" inverse="true" cascade="save-update" table="student_course">--中间表名称
<key column="course_id"></key> <many-to-many class="com.suxiaolei.hibernate.pojos.Student" column="student_id"></many-to-many> </set> </class> </hibernate-mapping>
