方法一:
//多条件组合查询
public List<Customer> findMoreCondition(Customer customer) {
//1-使用hibernate模板里面find方法实现
//拼接hql语句
String hql = "from Customer where 1=1";
//创建list集合,如果值不为空,就把值设置到list里面
List<Object> p = new ArrayList<Object>();
//判断条件值是否为空,如果不为空就拼接
if(customer.getCustName()!=null && !"".equals(customer.getCustName())){
hql += " and custName=?";
p.add(customer.getCustName());
}
if(customer.getCustLevel()!=null && !"".equals(customer.getCustLevel())){
hql += " and custLevel=?";
p.add(customer.getCustLevel());
}
if(customer.getCustSource()!=null && !"".equals(customer.getCustSource())){
hql += " and custSource=?";
p.add(customer.getCustSource());
}
System.out.println("hql:"+hql);
System.out.println("list:"+p);
return (List<Customer>) this.getHibernateTemplate().find(hql, p.toArray());
}
方法二(使用较多):
public List<Customer> findMoreCondition(Customer customer) {
//2.使用离线对象
DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);
//判断条件值是否为空
if(customer.getCustName()!=null&&!"".equals(customer.getCustName())){
//对属性设置值
criteria.add(Restrictions.eq("custName", customer.getCustName()));
}
/*if(customer.getCustLevel()!=null && !"".equals(customer.getCustLevel())){
criteria.add(Restrictions.eq("custLevel", customer.getCustLevel()));
}*/
if(customer.getCustSource()!=null && !"".equals(customer.getCustSource())){
criteria.add(Restrictions.eq("custSource", customer.getCustSource()));
}
return (List<Customer>) this.getHibernateTemplate().findByCriteria(criteria);
}