MyBatis的模糊查詢mapper.xml的寫法講解
MyBatis模糊查詢mapper.xml的寫法
模糊查詢語句不建議使用${}的方式,還是建議采用MyBatis自帶的#{}方式,#{}是預(yù)加載的方式運行的,比較安全,${}方式可以用但是有SQL注入的風(fēng)險?。?!
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為傳遞進(jìn)來的參數(shù),bind元素的value屬性將傳進(jìn)來的參數(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,
應(yīng)該寫成: "%"#{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 標(biāo)簽,對字符串進(jìn)行綁定,然后對綁定后的字符串使用 like 關(guān)鍵字進(jìn)行模糊查詢 -->
<if test="email != null">
<bind name="pattern" value="'%'+email+'%'"/>
and email like #{pattern}
</if>
</where>
</select>
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java根據(jù)前端返回的字段名進(jìn)行查詢數(shù)據(jù)的實現(xiàn)方法
在Java后端開發(fā)中,我們經(jīng)常需要根據(jù)前端傳遞的參數(shù)(如字段名)來動態(tài)查詢數(shù)據(jù)庫中的數(shù)據(jù),這種需求通常出現(xiàn)在需要實現(xiàn)通用查詢功能或者復(fù)雜查詢接口的場景中,所以本文介紹了Java根據(jù)前端返回的字段名進(jìn)行查詢數(shù)據(jù)的實現(xiàn)方法,需要的朋友可以參考下2024-12-12
關(guān)于SpringBoot配置文件加載位置的優(yōu)先級
這篇文章主要介紹了關(guān)于SpringBoot配置文件加載位置的優(yōu)先級,我們也可以通過spring.config.location來改變默認(rèn)的配置文件位置,項目打包好后,我們可以通過命令行的方式在啟動時指定配置文件的位置,需要的朋友可以參考下2023-10-10
SpringBoot大學(xué)心理服務(wù)系統(tǒng)實現(xiàn)流程分步講解
本系統(tǒng)主要論述了如何使用JAVA語言開發(fā)一個大學(xué)生心理服務(wù)系統(tǒng) ,本系統(tǒng)將嚴(yán)格按照軟件開發(fā)流程進(jìn)行各個階段的工作,采用B/S架構(gòu),面向?qū)ο缶幊趟枷脒M(jìn)行項目開發(fā)2022-09-09

