MyBatis的模糊查詢mapper.xml的寫法講解
更新時間:2021年09月30日 10:51:29 作者:唯愛沁源
這篇文章主要介紹了MyBatis的模糊查詢mapper.xml的寫法講解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
MyBatis模糊查詢mapper.xml的寫法
模糊查詢語句不建議使用${}的方式,還是建議采用MyBatis自帶的#{}方式,#{}是預加載的方式運行的,比較安全,${}方式可以用但是有SQL注入的風險?。。?/p>
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數據庫的語句
采用concat()函數,它可以將多個字符串連接成一個字符
<select>
select * from table where name like concat('%',#{name},'%')
</select>
3.適用于所有數據庫的則采用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為傳遞進來的參數,bind元素的value屬性將傳進來的參數和 '%' 拼接到一起后賦給name屬性的user_name,之后可以在select語句中使用user_name這個變量。
bind元素也支持傳遞多個參數
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)函數將兩個參數連接 -->
<if test="phone != null">
and phone like concat(concat("%",#{phone}),"%")
</if>
<!--方法三: 使用 bind 標簽,對字符串進行綁定,然后對綁定后的字符串使用 like 關鍵字進行模糊查詢 -->
<if test="email != null">
<bind name="pattern" value="'%'+email+'%'"/>
and email like #{pattern}
</if>
</where>
</select>
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

