在檢索的時候我們經常會遇到多條件查詢的情況,這種情況有時候很棘手,下面是我的解決方法。
先舉個例子:查詢條件:登錄名,ip地址。類別,登陸時間(startTime endTime)
<div id="tb" style="padding:3px"> <form id="searchForm"> <span>登錄名</span> <input id="loginName" style="border:1px solid #ccc" name="loginName" > <span>IP地址</span> <input id="ip" style="border:1px solid #ccc" name="ip"> <span>類別</span> <select id="combobox" class="easyui-combobox" name="type" style="width:100px;"> <option >登錄系統</option> <option>退出系統</option> </select> <span>登陸時間</span> <input name="startTime" class="easyui-datetimebox" editable="false" style="border:1px solid #ccc">-<input name="endTime" class="easyui-datetimebox" editable="false" style="border:1px solid #ccc"> <a href="#" class="easyui-linkbutton" iconCls="icon-search" onclick="doSearch()" >檢索</a> <a href="#" class="easyui-linkbutton" iconCls="icon-redo" onclick="clear()" >重置檢索</a> </form> </div>
遇到這種情況的話很棘手。分析如下
1)在表單提交的時候驗證,規定那個不能爲空什麼的,但是這樣的話就會出現一個問題,有時候我們並不需要這個條件,也就是說某個條件可空可不空,每個條件都是獨立的,可以組合條件查詢,可以單獨查詢這樣的話驗證沒有多大意義,違背了我們的初衷(單兵作戰與團伙作案,哈哈哈)。
2)所以我們在後臺接受這些條件,並根據條件寫出查詢語句,查詢語句是重點。
1.如果沒有條件的話:select * from User ;
2.有條件的話Select * from User where 條件1 and 條件2 and 條件3
這時候出現了問題,第一種情況你必須判斷這5個條件同時爲空,第二種更麻煩。
where 1=1閃亮登場,將1和2結合成一種情況。代碼:
public String findHql(String sort,String order,UserHistory model, String startTime, String endTime){ String hql="from UserHistory uh where 1=1 "; if(model.getLoginName()!=null){ hql+=" and uh.loginName='"+model.getLoginName()+"'"; } if(model.getType()!=null){ hql+=" and uh.type='"+model.getType()+"'"; } if(model.getIp()!=null){ hql+=" and uh.ip='"+model.getIp()+"'"; } if(startTime.length()>0){ hql+=" and uh.loginTime>='"+startTime+"'"; } if(endTime.length()>0){ hql+=" and uh.loginTime<='"+endTime+"'"; } hql+=" order by "+sort+" "+order; return hql; }
說了這麼多的廢話無非就是爲了說明where 1=1這個條件的重要性。尤其是在多條件查詢時。