HQL多条件查询判断的问题

有客户、编号、发货日期、截止日期4个查询条件,查询出对应的记录的条数,我的HQL查询代码如下:
[code="java"]
public Long getCount(String soNumber, Long customerID, Date startDate, Date endDate) {
String hql = "select count(*) from SalesOrder salesOrder where 1=1";
if(!"".equals(soNumber)){
hql =hql+" and sal.soNumber=?";
}
if(customerID!=null){
hql= hql+" and sal.customer.customerID =?";
}if(startDate!=null){
hql=hql+" and sal.jiaohuoriqi >=? and sal.jiaohuoriqi<=?";
}

Object[] count =new Object[]{soNumber,customerID,startDate,endDate};
return (Long)this.getHibernateTemplate().find(hql,count).get(0);
}
[/code]我的问题是 我把参数放在了数组里面,对应不同的情况数组怎么判断?

参数直接放进来就好了啊

public Long getCount(String soNumber, Long customerID, Date startDate, Date endDate) {
String hql = "select count(*) from SalesOrder salesOrder where 1=1";
if(!"".equals(soNumber)){
hql =hql+" and sal.soNumber="+soNumber;
}
if(customerID!=null){
hql= hql+" and sal.customer.customerID ="+customerID;
}if(startDate!=null){
hql=hql+" and sal.jiaohuoriqi >='"+startDate+"' and sal.jiaohuoriqi<= '"+endDate+"'";
}

      return (Long)this.getHibernateTemplate().find(hql).get(0);
}

你这个是一个查询参数匹配的问题。当有一个参数条件不成立的时候你的数组要-1;结合这样的特点,其实你可以考虑使用可变集合List,而不是数组;
[code="java"]
public Long getCount(String soNumber, Long customerID, Date startDate, Date endDate) {
List paramList = new ArrayList();
String hql = "select count(*) from SalesOrder salesOrder where 1=1";

if(!"".equals(soNumber)){

hql =hql+" and sal.soNumber=?";
paramList.add(soNumber);
}

if(customerID!=null){

hql= hql+" and sal.customer.customerID =?";
paramList.add(customerID);
}
if(startDate!=null){

hql=hql+" and sal.jiaohuoriqi >=? and sal.jiaohuoriqi<=?";
paramList.add(startDate);
paramList.add(endDate);
}

      return (Long)this.getHibernateTemplate().find(hql,paramList.toArray()).get(0);  
}

[/code]

一个问号对应一个参数,你上面拼接,?不定,参数固定4个,肯定不行的

还是直接将参数写到hql语句里

沙发都帮你改了,就是那样子的

直接放进去肯定是不行的,这说明你写代码的不严谨,要防止用户SQL注入问题,最好是用参数方式。也省事,很多潜在BUG,比如说用户输入 “单引号”,你转换的sql就有问题了。