双向关联的1对1关系:
public class People {
private Integer id;
private String name;
private int age;
private Student student;
}
public class People {
private Integer id;
private String name;
private int age;
private Student student;
}
配置文件:
<class name="People" table="people">
......
//使用many-to-one是因为是双向关联的关系,student一方可能会有多个对应这一个
<many-to-one name="student" class="Student" cascade="all"
unique="true">
//在people类中对应的属性student在people表中对应的列为studentid
<column name="studentid"></column>
</many-to-one>
</class>
<class name="Student" table="student">
......
<one-to-one name="people" class="People" property-ref="student" cascade="all" ></one-to-one>
</class>
1对多或多对1的关系:
//多端
public class Address {
private Integer id;
private String stress;//街道
private String room; //门牌号
private People people;
}
public class People {
private Integer id;
private String name;
private int age;
private Set<Address> address = new HashSet<>(); //1端
}
配置文件:
<class name="Address" table="address">
......
<!-- 注意insert应该写在1方还是在多多方,如何insert的位置不对,会造成外键不能写入为null的情况 -->
<many-to-one name="people" class="People" cascade="all" insert="true">
//在address表中pid则对应address类中的people-----指定外键名
<column name="pid"></column>
</many-to-one>
</class>
<class name="People" table="people">
......
<!-- 1对多关系的配置:1方的建写到多端 -->
<set name="address" cascade="all">
//告诉People表,查找address时主要看外键pid----声明外键及外键所在类
<key>
<column name="pid"></column>
</key>
<one-to-many class="Address"/>
</set>
</class>
多对多关系:
public class Student {
private int id;
private Timestamp date;
private String room;
private Set<Teacher> teachers = new HashSet<>();
}
public class Teacher {
private int id;
private String study;
private Set<Student> students = new HashSet<>();
}
配置文件:
<class name="Student" table="student">
......
<set name="teachers" table="stu_teach" cascade="save-update">
//声明teachers所对应的外键为teachid
<key column="teachid"></key>
<many-to-many class="Teacher" column="stuid"></many-to-many>
</set>
</class>
<class name="Teacher" table="teacher">
......
<set name="students" table="stu_teach" cascade="save-update">
<key column="stuid"></key>
<many-to-many class="Student" column="teachid"></many-to-many>
</set>
</class>