mybatis-03学习复杂查询

1,259 阅读2分钟

mybatis-03学习复杂查询

讲到复杂查询,在mybatis中就要用到resultMap结果映射,之前用到单表简单查询,用一个resultType就可以满足了,但一旦是一些连接查询等复杂查询时候,resultMap作用就体现出来了。下面重点讲下这个MyBatis中最强大的元素。

resultMap介绍

显示resultMap的元素概念,下图是官网中的讲解图,重点讲下关联(association)和集合(collection)

image-20200518151113180

关联(association)

image-20200518212633184

关联(association)元素处理“有一个”类型的关系,同时MyBatis 有两种不同的方式加载关联:

  1. 嵌套的查询,和sql中的子查询类似
  2. 根据结果来映射

集合(collection)

实例使用resultMap的关联查询

正常的MySQL查询-连接查询,但是在mybatis怎么实现呢,接下来来讲下两种方式去实现。

image-20200518212358659

方式一 嵌套查询

StudentMapper.xml

<mapper namespace="com.yhy.dao.StudentMapper">

    <select id="getStudent" resultMap="StudentTeacher">
    select * from student;
    </select>

    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="id" />
        <result property="name" column="name" />

<!--        有时需要处理一些复杂的数据查询,多表查询等,就需要用到assoction-->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>

    <select id="getTeacher" resultType="Teacher">
        select  * from  teacher where id = #{id};
    </select>


</mapper>

结果,这个结果就类似sql中的子查询,一个结果中嵌套另一个结果

image-20200518151811158

方式二 按照结果处理

StudentMapper.xml修改成以下的形式,其实这样的形式更加容易理解。

!--采用连接查询的方法-->
    <select id="getStudent2" resultMap="StudentTeacher2">
    select s.id sid,s.name sname, t.name tname
    from student s , teacher t
    where s.tid = t.id;
    </select>

    <resultMap id="StudentTeacher2" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

结果也一样

image-20200518212227344

JavaType--用来指定实体类中的属性

ofType--用来指定映射到List或者集合中的pojo类型,泛型中的约束类型

最后

无论使用什么的方式,保持代码的可读性和效率是很关键的。