property:对象、成员变量属性的名称
column:数据库字段名称
javaType:对象属性的类型
ofType:集合中的泛型信息
association:一个复杂类型的关联
collection:一个复杂类型的集合
多对一:
子查询:就是SQL里面的嵌套查询,我们现在有两张表,就需要查两次。由于是多个学生关联一个老师,所以这里用 association 标签,关联标签返回的是对象属性的类型(javaType)。我们首先要查询出所有的学生信息,因为学生实体类中除了变量属性还有对象属性(学生所关联的Teacher对象属性),变量属性可以很好地对应数据库的字段名,而对象属性需要用结果集映射。然后,根据查询出的学生tid,寻找对应的老师。因为映射之后,相应的tid已经有了,所以id=#{tid}括号里面的可以随意填写。
<mapper namespace="com.dao.StudentMapper">
<select id="getStudent" resultMap="StudentTeacher">
select *
from mybatis.student;
</select>
<resultMap id="StudentTeacher" type="student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="teacher">
select *
from mybatis.teacher
where id = #{tid}
</select>
按结果嵌套查询:按结果嵌套查询就是SQL里面的联表查询,利用的是笛卡尔积将两张表关联,只需查一次,无论是效率方面还是理解层面上,按结果嵌套查询都要优于子查询,所以这里推荐使用第二种。可以很清楚地看出,按结果嵌套查询是先把查询完整语句给出,然后再对取别名的字段进行映射。对于对象属性的利用association进行字段对应。你可以这样理解,两张表都有name和id属性,如果不用association标签,两个name和id属性势必会冲突。
<select id="getStudent2" resultMap="StudentTeacher1">
select s.id sid, s.name sname, t.name tname,t.id tid
from mybatis.teacher t,
mybatis.student s
where s.tid = t.id
</select>
<resultMap id="StudentTeacher1" type="Student">
<result property="name" column="sname"/>
<result property="id" column="sid"/>
<association property="teacher" javaType="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
</association>
</resultMap>
一对多查询
按结果嵌套查询:
<select id="getTeacher" resultMap="TeacherStudent">
select t.id tid, t.name tname, s.name sname, s.id sid
from mybatis.teacher t,
mybatis.student s
where t.id = s.tid
</select>
<!--javaType=""指定属性的类型!集合中的泛型信息我们用ofType来获取-->
<resultMap id="TeacherStudent" type="Teacher">
<result property="name" column="tname"/>
<result property="id" column="tid"/>
<collection property="students" ofType="Student">
<result property="name" column="sname"/>
<result property="id" column="sid"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
子查询:
<select id="getTeacher2" resultMap="TeacherStudent2">
select *
from mybatis.teacher
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<result column="id" property="id"/>
<result column="name" property="name"/>
<collection property="students" javaType="Arraylist" ofType="Student" select="getStudent" column="id"/>
</resultMap>
<select id="getStudent" resultType="Student">
select *
from mybatis.student
where tid = #{tid}
</select>