一对一的表关系
实现一对一映射 这时需要我们在类上设置好对应的对象属性
然后在映射文件的resultMap中 通过association标签进行配置
配置的方法有两种:
一种是通过联表查询 直接将两张表的数据一次都查询出来,
然后将副表的字段在association标签内进行映射
一种是通过对association标签设置select属性和column属性
让要对本条记录进行映射时 再次进行一次根据我们设置的column属性的值为参数的子查询
并将子查询的结果集映射成我们的实体类对象 再赋值给我们对应的属性上
完成一条记录的映射后 循环进行下一条记录的组装
两种方式的区别:
第一种方式实际上只对数据库进行了一次查询
而第二种方式对数据库进行多次的请求访问
<!-- 一对一 -->
<!-- 方式一 联表查询 -->
<resultMap type="Student" id="oneToOne">
<id column="sId" property="sId"/>
<result column="sName" property="sName"/>
<!-- 属性是个实体类对象 -->
<association property="teacher" javaType="Teacher">
<id column="tId" property="tId"/>
<result column="tName" property="tName"/>
</association>
</resultMap>
<select id="selectOneToOne" resultMap="oneToOne">
select * from student s
left join teacher t
on s.teacherId = t.tid;
</select>
<!-- 方式二 -->
<resultMap type="Student" id="findOneToOne">
<id column="sId" property="sId"/>
<result column="sName" property="sName"/>
<association property="teacher" select="findTeacher" column="teacherId"></association>
</resultMap>
<select id="findOneToOne" resultMap="findOneToOne">
select * from student
</select>
<resultMap type="Teacher" id="teacherMap">
<id column="tId" property="tId"/>
<result column="tName" property="tName"/>
</resultMap>
<select id="findTeacher" resultMap="teacherMap" parameterType="int">
select * from teacher
where tid = #{0}
</select>