溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

MyBatis中如何實現(xiàn)模糊查詢mapper.xml

發(fā)布時間:2021-09-30 13:34:31 來源:億速云 閱讀:362 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹MyBatis中如何實現(xiàn)模糊查詢mapper.xml,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

    MyBatis模糊查詢mapper.xml的寫法

    模糊查詢語句不建議使用${}的方式,還是建議采用MyBatis自帶的#{}方式,#{}是預加載的方式運行的,比較安全,${}方式可以用但是有SQL注入的風險?。?!

    1.直接傳參

    在controller類中

    String id = "%"+ id +"%";
    String name = "%"+ name +"%";
    dao.selectByIdAndName(id,name);

    在mapper.xml映射文件中

    <select>
        select * from table wherer id=#{id} or name like #{name}
    </select>

    2.針對MySQL數(shù)據(jù)庫的語句

    采用concat()函數(shù),它可以將多個字符串連接成一個字符

    <select>
        select * from table where name like concat('%',#{name},'%')
    </select>

    3.適用于所有數(shù)據(jù)庫的則采用MyBatis的bind元素

    public xx selectByLike(@Param("_name") String name);
    <select id="selectByLike">
        <bind name="user_name" value="'%' + _name + '%'"/>
        select * from table where name like #{user_name}
    </select>

    其中_name為傳遞進來的參數(shù),bind元素的value屬性將傳進來的參數(shù)和 '%' 拼接到一起后賦給name屬性的user_name,之后可以在select語句中使用user_name這個變量。

    bind元素也支持傳遞多個參數(shù)

    public xx selectByLike(@Param("_name") String name, @Param("_note") String note);
    <select id="selectByLike">
        <bind name="user_name" value="'%' + _name + '%'"/>
        <bind name="user_note" value="'%' + _note + '%'"/>
        select * from table where name like #{user_name} and note like #{user_note}
    </select>

    MyBatis在xml中模糊查詢的常用的3種方式

    <!-- ******************** 模糊查詢的常用的3種方式:********************* -->
        <select id="getUsersByFuzzyQuery" parameterType="User" resultType="User">
            select <include refid="columns"/> from users
            <where>
                <!--
                    方法一: 直接使用 % 拼接字符串
                    注意:此處不能寫成  "%#{name}%" ,#{name}就成了字符串的一部分,
                    會發(fā)生這樣一個異常: The error occurred while setting parameters,
                    應該寫成: "%"#{name}"%",即#{name}是一個整體,前后加上%
                -->
                <if test="name != null">
                    name like "%"#{name}"%"
                </if>
                <!--方法二: 使用concat(str1,str2)函數(shù)將兩個參數(shù)連接 -->
                <if test="phone != null">
                    and phone like concat(concat("%",#{phone}),"%")
                </if>
                <!--方法三: 使用 bind 標簽,對字符串進行綁定,然后對綁定后的字符串使用 like 關(guān)鍵字進行模糊查詢 -->
                <if test="email != null">
                    <bind name="pattern" value="'%'+email+'%'"/>
                    and email like #{pattern}
                </if>
            </where>
        </select>

    以上是“MyBatis中如何實現(xiàn)模糊查詢mapper.xml”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

    向AI問一下細節(jié)

    免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI