欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

關(guān)于MyBatis模糊查詢的幾種實現(xiàn)方式

 更新時間:2023年05月01日 09:40:41   作者:柚子貓嶼  
在實際項目中,我們會經(jīng)常對數(shù)據(jù)做一些模糊查詢的操作,這時候就需要利用到 like字段,那么在Mybatis中,有哪些方式可以實現(xiàn)模糊查詢呢,需要的朋友可以參考下

一、模糊查詢的幾種實現(xiàn)方式

1.concat函數(shù)和#{}拼接的方式

student_name like concat('%',#{studentName},'%')

2.%和${}拼接的方式

student_name like '%${studentName}%'

3.concat函數(shù)和${}拼接的方式

student_name like concat('%','${studentName}','%')

4.||和#{}拼接的方式

student_name like '%'||#{studentName}||'%'

分析: (1)${}:表示拼接sql串,將接收到參數(shù)的內(nèi)容不加任何修飾拼接在sql中,可能引發(fā)sql注入。 (2)#{ }是預編譯處理,MyBatis在處理#{ }時,它會將sql中的#{ }替換為?,然后調(diào)用PreparedStatement的set方法來賦值,傳入字符串后,會在值兩邊加上單引號,使用占位符的方式提高效率,可以防止sql注入。因此最好使用#{ }方式。 (3)concat函數(shù)最好不要使用,最好使用||,因為在Oracle中,concat()只能對兩個字符串進行拼接(字符串多的話只能嵌套使用),而||可以對字符串無限拼接。

5.建議使用的方式

建議使用第四種哦,示例:

<if test="studentName != null and studentName !=''">
	and student_name like '%'||#{studentName}||'%'
</if>

二、用mybatis出現(xiàn)的一些問題

1.一般查詢條件的使用

在mapper文件里面關(guān)于查詢if的條件基本都要寫出兩種空值,否則就會在查詢時把其他不需要的數(shù)據(jù)也查出來。

錯誤示范:

<if test="studentName != null">
	and student_name = #{studentName}
</if>

正確示范:

<if test="studentName != null and studentName !=''">
	and student_name = #{studentName}
</if>

2.日期查詢條件的使用

這個是在寫日期查詢條件時,出現(xiàn)了日期只能修改,但不能為空的問題:

錯誤示范:

<if test="effDate != null and effDate !=''">
	and eff_date = #{effDate}
</if>
<if test="expDate != null and expDate !=''">
    and exp_date = #{expDate}
</if>

正確示范:去掉外面的if判空條件

and eff_date = #{effDate}
and exp_date = #{expDate}

3.排序問題

查詢時最好按id倒序,在修改之后不影響原有順序

比如:order by student_id desc

到此這篇關(guān)于關(guān)于MyBatis模糊查詢的幾種實現(xiàn)方式的文章就介紹到這了,更多相關(guān)MyBatis模糊查詢內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論