在检索的时候我们经常会遇到多条件查询的情况,这种情况有时候很棘手,下面是我的解决方法。

先举个例子:查询条件:登录名,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" οnclick="doSearch()"  >检索</a>
		<a href="#" class="easyui-linkbutton" iconCls="icon-redo" οnclick="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这个条件的重要性。尤其是在多条件查询时。