第一种:拼接hql语句方式:
1 //第一种方式:拼接hql语句实现 2 public List<Customer> findMoreCondition(Customer customer) { 3 //拼接hql语句 4 String hql = "from Customer where 1=1 "; 5 //创建list集合设置参数值 6 List<Object> listparam = new ArrayList<Object>(); 7 //判断customer条件值是否为空,如果不为空拼接hql语句 8 if(customer.getCustName()!=null && !"".equals(customer.getCustName())) { 9 hql += " and custName=?"; 10 //把值设置到list集合里面 11 listparam.add(customer.getCustName()); 12 } 13 if(customer.getCustLevel()!=null && !"".equals(customer.getCustLevel())) { 14 hql += " and custLevel=?"; 15 listparam.add(customer.getCustLevel()); 16 } 17 if(customer.getCustSource()!=null && !"".equals(customer.getCustSource())) { 18 hql += " and custSource=?"; 19 listparam.add(customer.getCustSource()); 20 } 21 //调用hibernate模板的方法实现查询 22 List<Customer> list = 23 (List<Customer>) this.getHibernateTemplate().find(hql, listparam.toArray()); 24 return list; 25 }
第二种:使用离线对象方式:
1 //条件查询 离线查询方式 2 @SuppressWarnings("all") 3 public List<LinkMan> findmoreCondition(LinkMan linkMan) { 4 DetachedCriteria criteria = DetachedCriteria.forClass(LinkMan.class); 5 if(linkMan.getLkmName()!=null && !"".equals(linkMan.getLkmName())){ 6 criteria.add(Restrictions.eq("lkmName", linkMan.getLkmName())); 7 } 8 if(linkMan.getCustomer().getCid()!=null && linkMan.getCustomer().getCid()>0){ 9 criteria.add(Restrictions.eq("customer.cid", linkMan.getCustomer().getCid())); 10 } 11 return (List<LinkMan>) this.getHibernateTemplate().findByCriteria(criteria); 12 }