一、結論
這里先給大家看一下結論
oracle 中,拼接模糊查詢的正確寫法
1
2
3
4
5
6
|
select a.user_id, a.user_name from user a and a.user_name like concat(concat( '%' , 'w' ), '%' ) 或者 and a.user_name like '%' || 'w' || '%' |
mybatis 中,拼接模糊查詢的正確寫法
1
2
3
4
5
6
7
8
9
10
11
12
|
<select id= "selectbyname" resultmap= "baseresultmap" > select a.user_id, a.user_name from t_base_user_info a < if test= "username != null" > and a.user_name like '%' || #{username} || '%' </ if > 或者 < if test= "username != null" > and a.user_name like concat(concat( '%' , '${username}' ), '%' ) </ if > </select> |
注意 mybatis 中,拼接模糊查詢的用法
,是將傳入的值當做字符串的形式。所以拼接的時候 #{username}
默認自帶引號。例如: ${username}
直接轉為 ‘zhen'。
,是將傳入的數據直接顯示生成sql語句。所以拼接的時候
,是將傳入的數據直接顯示生成sql語句。所以拼接的時候
{username}
沒有默認引號。例如:${username}
直接轉為 zhen 。
二、技巧:
剛開始寫的時候一直報錯,報錯信息是這樣的:
"message": "request processing failed; nested exception is org.mybatis.spring.mybatissystemexception: nested exception is org.apache.ibatis.type.typeexception: could not set parameters for mapping: parametermapping{property='username', mode=in, javatype=class java.lang.string, jdbctype=null, numericscale=null, resultmapid='null', jdbctypename='null', expression='null'}. cause: org.apache.ibatis.type.typeexception: error setting non null for parameter #1 with jdbctype null . try setting a different jdbctype for this parameter or a different configuration property. cause: java.sql.sqlexception: 無效的列索引",
我的寫法是這樣的:
1
2
3
4
5
6
7
8
9
10
11
12
|
< if test= "_parameter != null" > -- and a.user_name like concat( '%' , '#{username}' , '%' ) and a.user_name = #{username} </ if > <!-- < if test= "usertype != null" > and a.user_type = #{usertype} </ if > < if test= "mobilephoneno != null" > and a.mobile_phone_no like concat( '%' , '#{mobilephoneno}' , '%' ) </ if > < if test= "roleid != null" > and b.role_id = #{roleid}<br> </ if >--> |
后來我徹底凌亂了,于是就從頭開始寫,結果就好了。
小結:
出現的報錯可能跟我之前寫了太多的if 判斷語句有關,于是先寫一個簡單的
1
2
3
|
< if test= "username != null" > and a.user_name like '%' || #{username} || '%' </ if > |
這個可以執行,其他再有什么條件加進來,稍微修改之后,都可以正常運行。
1
2
3
4
5
6
7
8
9
10
11
12
|
< if test= "username != null" > and a.user_name like concat(concat( '%' , '${username}' ), '%' ) </ if > < if test= "usertype != null" > and a.user_type = #{usertype} </ if > < if test= "mobilephoneno != null" > and a.mobile_phone_no like '%' || #{mobilephoneno} || '%' </ if > < if test= "baseroleinfo.roleid != null" > and b.role_id = #{baseroleinfo.roleid} </ if > |
總結
以上所述是小編給大家介紹的mybatis 中 oracle 的拼接模糊查詢,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://blog.csdn.net/ancdc/article/details/81479622