以学生表(Student)和教师表(Teacher)为例:
其中tid为外键约束
多对一处理
- 按查询嵌套处理
(相当于sql中的子查询)
思路:
1.查询所有的学生信息
2.根据查询出来的学生信息中的tid,查找教师信息:子查询
/**
* 查询学生信息以及对应的老师信息
* @return
*/
public List<Student> getStudentInfo();
/**
* 获取学生表tid列名对应的教师信息
* @param id 每个学生对应的教师编号
* @return
*/
public Teacher getTeacher(int id);
<resultMap id="StudentTeacher" type="Student">
<!--
复杂的属性需要单独进行处理
association:对象
collection:集合
-->
<!--
association:关联属性
property:表示java类中的属性名
javaType:表示property属性对应的类型
column:数据库中表的列名
select:嵌套查询
-->
<association property="teacher" javaType="Teacher" column="tid"
select = "getTeacher"/>
</resultMap>
<!--获取学生信息-->
<select id="getStudentInfo" resultMap="StudentTeacher">
select id,name,tid from student
</select>
<!--获取每个学生对应的教师信息-->
<select id="getTeacher" resultType="Teacher" parameterType="int">
select id,name from teacher where id = #{id}
</select>
- 按结果嵌套处理
(相当于sql中的联表查询)
<!--按照结果嵌套处理-->
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/><!--此时的column用的是sql语句中的别名-->
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
<select id="getStudentInfo2" resultMap="StudentTeacher2">
select student.id sid,student.name sname,teacher.name tname from student,teacher where student.tid = teacher.id
</select>
一对多处理
教师的实体类为:
学生的实体类为:
- 按结果嵌套处理
/**
* 获取指定老师的及对应的所有学生信息
* @param id 教师编号
* @return
*/
public List<Teacher> getTeacherAndStudents(int id);
<resultMap id="TeacherStudents" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--
集合的话,使用collection!
JavaType和ofType都是用来指定对象类型的
JavaType是用来指定pojo中属性的类型
ofType指定的是映射到list集合属性中pojo的类型。
-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
</collection>
</resultMap>
<select id="getTeacherAndStudents" resultMap="TeacherStudents" parameterType="int">
select teacher.id tid, teacher.name tname, student.id sid, student.name sname from student,teacher where teacher.id = student.tid and teacher.id = #{id}
</select>
- 按查询嵌套处理
<resultMap id="TeacherStudents2" type="Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="students" javaType="ArrayList" ofType="Students"
select="getStudents" column="id"/>
</resultMap>
<select id="getTeacherAndStudents2" resultMap="TeacherStudents2" parameterType="int">
select id,name from teacher where id = #{id}
</select>
<select id="getStudents" resultType="Student">
select id,name,tid from student where tid = #{tid}
</select>
注意点:
1、关联-association(一对一和多对一)
2、集合-collection(一对多)
3、JavaType和ofType都是用来指定对象类型的
-
JavaType是用来指定pojo中属性的类型
-
ofType指定的是映射到list集合属性中pojo的类型。