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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM