之前一直是用mybatis進行sql查詢時,一般都是用generator逆向生產的代碼來進行查詢。
現在遇到了一個業務問題,我們需要進行對不同的條件分別進行模糊查詢,首先我想到的就是根據對需要進行模糊查詢的字段進行判斷,然后調用example的方式進行查詢條件的注入。
對于string類型的數據可以有like查詢這個方法,但是integer或者long這種數據類型的話就沒有了,得需要自己動手寫。
但是呢,我利用generator生成的代碼example方式進行模糊查詢時確無法實現,原因不太清楚,但是感覺代碼沒問題。
于是,只能我們自己手動寫sql語句了。
但是呢,每個查詢條件都寫一個查詢語句的話,簡單歸簡單,但是太麻煩。
那么,我們能不能利用一個查詢來實現對不同字段的模糊查詢呢?
我的方法
1。首先,定義search類,有查詢字段type,和查詢條件condition,利用這個類將數據傳入sql查詢中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public class searchtype { private string type; private string condition; public string gettype() { return type; } public void settype(string type) { this .type = type; } public string getcondition() { return condition; } public void setcondition(string condition) { this .condition = condition; } } |
定義好類后,我們在service中調用mapper查詢方法
1
2
3
4
5
6
7
8
9
10
11
12
|
public list searchuser(string type,string condition) { searchtype search = new searchtype(); search.setcondition(condition); search.settype(type); //模糊查詢各字段 list<mkuser> list = usermapper.selectwithconditionlike(search); return list; } |
這里的mkuser是我們查詢結果后存儲數據的類
下面看看mapper.xml是如何實現的
1
2
3
4
5
6
|
<select id= "selectwithconditionlike" resultmap= "baseresultmap" parametertype= "com.moka.common.pojo.searchtype" > select userid ,username ,we_name ,we_number ,tel_number ,updatetime ,invite_number ,purchased_total from mk_user where ${type} like concat(concat( '%' ,#{condition}), '%' ) </select> |
關于為什么一個地方是${},另一個是#{},自己查詢這兩個的區別。
注意數據庫中的字段跟mkuser類中字段的對應,
我利用baseresultmap進行了對應。
這樣就搞定了。
mybaits generator 模糊查詢 (like)的使用方式
like 使用
使用like時如果不手動拼接 % 等上去的話很難達到模糊搜索的要求,默認生成的sql語句如下:
如傳入變量是 paramsvalue
1
|
select count(*) from table where (table_a like paramsvalue) |
由此可得,我們可以給傳入的變量手動拼接 %,也就是說
1
|
paramsvalue = "%" + paramsvalue + "%" |
之后再傳入 則可以達到模糊匹配的效果,當然這種前后都加 % 的做法盡量避免使用,數據量大的情況下檢索效果不會太好,因為會進行全表檢索,而不使用索引。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/melissa_heixiu/article/details/60879122