多条件组合查询

方法一:

//多条件组合查询
    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);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值