Mybatis之关联查询及动态SQL

前言

  实际开发项目中,很少是针对单表操作,基本都会联查多表进行操作,尤其是出一些报表的内容。此时,就可以使用Mybatis的关联查询还有动态SQL。前几篇文章已经介绍过了怎么调用及相关内容,因此这里只说明核心内容SQL映射文件的配置。

一对一关联

<association /> JavaType是用来指定pojo中属性的类型
此处采用两种方式进行关联查询,一种是嵌套结果,一种是嵌套查询。
<!-- 根据班级id查询班级和教师信息 -->
    <select id="getClass" resultMap="ClassResultMap">
        select *
        from class as c
        left join
        teacher as t on c.teacher_id = t.t_id
        where c.c_id
        = #{id}
    </select>

    <!-- 嵌套结果 -->
    <resultMap type="Classes" id="ClassResultMap">
        <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>

    <select id="getClass2" parameterType="int"
        resultMap="ClassResultMap2">
        select * from class where c_id=#{id}
    </select>


    <!-- 嵌套查询 -->
    <resultMap type="Classes" id="ClassResultMap2">
        <id property="id" column="c_id" />
        <result property="name" column="c_name" />
        <association property="teacher" column="teacher_id"
            select="getTeacher" />
    </resultMap>

    <select id="getTeacher" parameterType="int" resultType="Teacher">
        SELECT
        t_id id, t_name name from teacher where t_id=#{id}
    </select>

一对多关联

<collection /> ofType指定的是映射到list集合属性中pojo的类型
<select id="getClass3" parameterType="int"
        resultMap="ClassResultMap3">
        select *
        from class c
        left join teacher t on c.teacher_id =
        t.t_id
        left join student
        s on c.c_id = s.class_id
        where c.c_id = #{id}
    </select>

    <resultMap type="Classes" id="ClassResultMap3">
        <id property="id" column="c_id" />
        <result property="name" column="c_name" />
        <association property="teacher" column="teacher_id"
            javaType="Teacher">
            <id property="id" column="t_id" />
            <result property="name" column="t_name" />
        </association>
        <collection property="students" ofType="Student">
            <id property="id" column="s_id" />
            <result property="name" column="s_name" />
        </collection>
    </resultMap>

动态SQL

  使用Mybatis的动态SQL特性可以很容易的串联SQL。if choose(when otherwise) foreach trim>。更为细致的介绍不再赘述,Mybatis3官方参考文档中以详细介绍。

    <!-- 用户的条件查询 姓名模糊查询 -->
    <select id="selectUserByCondition" parameterType="UserCondition"
        resultType="User">
        select * from users
        where age &lt;= #{maxAge} and age &gt;= #{minAge}
        <if test='name!="%null%"'>
            and name like #{name}
        </if>
    </select>

猜你喜欢

转载自www.cnblogs.com/lyc-smile/p/9070957.html