MyBatis的模糊查詢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 關鍵字進行模糊查詢 --> <if test="email != null"> <bind name="pattern" value="'%'+email+'%'"/> and email like #{pattern} </if> </where> </select>
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
RequestContextHolder.getRequestAttributes()空指針問題及解決
這篇文章主要介紹了RequestContextHolder.getRequestAttributes()空指針問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01Java concurrency之集合_動力節(jié)點Java學院整理
Java集合主體內(nèi)容包括Collection集合和Map類;而Collection集合又可以劃分為List(隊列)和Set(集合),有需要的小伙伴可以參考下2017-06-06Gradle進階使用結合Sonarqube進行代碼審查的方法
今天小編就為大家分享一篇關于Gradle進階使用結合Sonarqube進行代碼審查的方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12修改SpringBoot 中MyBatis的mapper.xml文件位置的過程詳解
由于MyBatis默認的mapper.xml的掃描位置是resource文件下,但是不可能整個項目的mapper.xml文件都放在resource下,如果文件較少還行,但是如果文件比較多,太麻煩了,所以本文給大家介紹了修改SpringBoot 中MyBatis的mapper.xml文件位置的過程,需要的朋友可以參考下2024-08-08Spring?+?ECharts實現(xiàn)數(shù)據(jù)可視化的案例詳解
Apache?ECharts是一個基于?JavaScript?的開源可視化圖表庫,在網(wǎng)頁上實現(xiàn)數(shù)據(jù)的可視化,非常好用,本文將通過一個簡單的demo來給大家介紹一下Spring?+?ECharts如何數(shù)據(jù)可視化,需要的朋友可以參考下2023-07-07