在.xml文件中模糊查詢的常用的3種方法


我經常使用的模糊查詢的方法是:

<!-- ******************** 模糊查詢的常用的3種方式:********************* -->
    <select id="getUsersByFuzzyQuery" parameterType="User" resultType="User">
        select <include refid="columns"/> from users
        <where>
            <if test="name != null">
                name like "%"#{name}"%"
            </if>
            <!--方法二: 使用concat(str1,str2)函數將兩個參數連接 -->
            <if test="phone != null">
                and phone like concat(concat("%",#{phone}),"%")
            </if>
        </where>
    </select>

因為這種使用兩個連接符進行連接起來,看起來更好看一下吧。

還有其他兩種方式:

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

就是這兩種方式。我個人覺得還是第二種更好一下,比第一種規范,比第二種簡潔。


免責聲明!

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



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