<mapper namespace="com.itheima.mapper.TbStudentMapper"> <!--一对一关联查询,使用级联属性,其中tbTeacher是TbStudent的属性--> <resultMap id="myStuAndTea" type="com.itheima.pojo.TbStudent"> <id column="u_id" property="uId"></id> <result column="u_name" property="uName"></result> <result column="sex" property="sex" ></result> <result column="t_id" property="tId"></result> <result column="id" property="tbTeacher.id"></result> <result column="t_name" property="tbTeacher.tName"></result> </resultMap> <select id="getStuAndTea" resultMap="myStuAndTea"> select * from tb_student stu,tb_teacher tch where stu.t_id=tch.id and stu.u_id=#{id} </select> </mapper>
DEBUG [main] - ==> Preparing: select * from tb_student stu,tb_teacher tch where stu.t_id=tch.id and stu.u_id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
TbStudent{uId=1, uName='zhangsan', sex='男', tId=101, tbTeacher=TbTeacher{id=101, tName='admin'}}
方式二:
<mapper namespace="com.itheima.mapper.TbStudentMapper"> <!--一对一关联查询,使用association对于单个对象的关联查询,tbTeacher是TbStudent的属性,javaType不可缺少--> <resultMap id="myStuAndTea" type="com.itheima.pojo.TbStudent"> <id column="u_id" property="uId"></id> <result column="u_name" property="uName"></result> <result column="sex" property="sex" ></result> <result column="t_id" property="tId"></result> <association property="tbTeacher" javaType="com.itheima.pojo.TbTeacher"> <id column="id" property="id"></id> <result column="t_name" property="tName"></result> </association> </resultMap> <select id="getStuAndTea" resultMap="myStuAndTea"> select * from tb_student stu,tb_teacher tch where stu.t_id=tch.id and stu.u_id=#{id} </select> </mapper>
方式三:
<mapper namespace="com.itheima.mapper.TbStudentMapper"> <!--一对一关联查询,使用association分步查询,前提,在TbTeacherMapper.xml的sql映射中有getTeacher的查询方法-->
<!--column的值是TbStudent中传过来的值,执行了两次查询-->
<resultMap id="myStuAndTea" type="com.itheima.pojo.TbStudent"> <id column="u_id" property="uId"></id> <result column="u_name" property="uName"></result> <result column="sex" property="sex" ></result> <result column="t_id" property="tId"></result> <association property="tbTeacher" select="com.itheima.mapper.TbTeacherMapper.getTeacher" column="t_id"> </association> </resultMap> <select id="getStuAndTea" resultMap="myStuAndTea"> select * from tb_student stu where stu.u_id=#{id} </select> </mapper>
DEBUG [main] - ==> Preparing: select * from tb_student stu where stu.u_id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - ====> Preparing: select id,t_name as tName from tb_teacher where id=?
DEBUG [main] - ====> Parameters: 101(Integer)
DEBUG [main] - <==== Total: 1
DEBUG [main] - <== Total: 1
TbStudent{uId=1, uName='zhangsan', sex='男', tId=101, tbTeacher=TbTeacher{id=101, tName='admin'}}DEBUG