MyBatis_一对一关联表查询(根据班级id查询班级信息(带老师的信息))
class表:
teacher表:
classMapper.xml文件,封装的对象复杂时,需要用到resultMap
<!-- 方式一:嵌套结果:使用嵌套结果映射来处理重复的联合结果的子集封装联
表查询的数据(去除重复的数据)
select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=1
-->
<select id="getClass" parameterType="int" resultMap="getClassMap">
SELECT * FROM class c , teacher t WHERE c.teacher_id = t.t_id AND c.c_id=#{id}
</select>
<resultMap type="Classes" id="getClassMap">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" javaType="Teacher">
<id property="id" column="t_id"/>
<result property="name" column="t_name"/>
</association>
</resultMap>
Association专门用来做一对一的(teacher)
<association property="teacher" javaType="Teacher">
<id property="id" column="t_id"/>
<result property="name" column="t_name"/>
</association>
Class对应的bean:
Teacher对应的bean:
用来做测试的实例:
查询结果: