mybatis 之 簡單動(dòng)態(tài)sql

1 什么是動(dòng)態(tài) sql

mybatis 對(duì) sql 語句進(jìn)行靈活操作,通過表達(dá)式進(jìn)行判斷,從而對(duì)sql進(jìn)行靈活的封裝。

2 if 的用法

需求:從學(xué)生表(students)中查詢用戶信息,對(duì)查詢條件進(jìn)行判斷,如果不為空,則進(jìn)行條件拼接。

mapper.xml

<mapper namespace="_4dynamicSql.StudentMapper">


    <select id="findStudents" resultType="_4dynamicSql.Student" 
                parameterType="_4dynamicSql.StudentVo">
        SELECT id,name,sal FROM students

        <!--
                使用where可以自動(dòng)省掉sql中的第一個(gè)and
        -->
        <where>
            <if test="studentCustom!=null">
                <if test=" studentCustom.name != null 
                        and studentCustom.name != ''">
                    AND name = #{studentCustom.name}
                </if>
                <if test="studentCustom.sal != null and   
                        studentCustom.sal != ''">
                    AND sal = #{studentCustom.sal}
                </if>
            </if>
        </where>
    </select>
</mapper>
3 sql片段引用

mybatis.xml

 <!--
        定義 sql 片段
        id:sql片段唯一標(biāo)示符
    -->
    <sql id="query_student_where" >
        <if test="studentCustom!=null">
            <if test=" studentCustom.name != null and   
                    studentCustom.name != ''">
                and name = #{studentCustom.name}
            </if>
            <if test="studentCustom.sal != null and 
                    studentCustom.sal != ''">
                AND sal = #{studentCustom.sal}
            </if>
        </if>
    </sql>


 <select id="findStudents" resultType="_4dynamicSql.Student" 
            parameterType="_4dynamicSql.StudentVo">
        SELECT id,name,sal FROM students
        <where>
            <include refid="query_student_where"/>
        </where>
    </select>
3 foreach

實(shí)現(xiàn)該sql語句的拼接
AND (id=1 OR id=2 OR id=4)

        <!--
            使用 foreach 遍歷傳入data
            collection:指定輸入對(duì)象中集合屬性
            item:每次遍歷的項(xiàng)
            open:開始遍歷時(shí)拼接的串
            close:結(jié)束時(shí)遍歷拼接的串
            separator:遍歷的兩個(gè)對(duì)象之間的串
        -->
        <foreach collection="data" item="item" open=" AND  (" close=")" 
                separator="OR">
            id=#{item}
        </foreach>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容