在昨天使用resultmap结果集解决属性和字段不一致导致查询出为null的情况,昨天针对的是简单查询,今天以多对一为例子,继续探究多对一复杂查询,主要涉及知识点为巩固resultmap使用以及其中的association。
思路:
1、先查询所有学生信息student
2、查询老师信息teacher
3、设置resultmap关联,如果属性为对象,则使用association,注意javatype、resulttype 均是全路径下的实体类
select 直接绑定查询老师teacher的sql语句
首先看下数据库字段:
实体类Teacher和Student
//Student实体类
public class Student {
private int id;
private String name;
private Teacher teacher ;
}
//Teacher实体类
public class Teacher {
private int id;
private String name;
}
从上面可以看出,Teacher实体类的teacher属性和teacher数据表中tid字段不一致,这里就需要我们将teacher属性使用resultmap结果集映射
<!--namespace对应全路径下的mapper-->
<mapper namespace="com.lizheng.dao.StudentMapper">
<select id="getStudent" resultMap="map">
select * from mybatis.student
</select>
<resultMap id="map" type="com.lizheng.pojo.Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="com.lizheng.pojo.Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="com.lizheng.pojo.Teacher">
select * from mybatis.teacher where id = #{tid}
</select>
</mapper>
还有另一种方法,先按照查询结果来写SQL,最后再使用resultmap映射
<select id="getStudent" resultMap="map">
select s.id sid,s.name sname, t.name tname from student s ,teacher t
where s.tid = t.id
</select>
<resultMap id="map" type="com.lizheng.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="com.lizheng.pojo.Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
这中方法相对简单些,不需要多谢查询teacher的SQL语句,实体类中有哪些属性就在javatype中返回这个属性 ,然后再嵌套result 查询teacher中的name属性
最终测试可以查询出: