Hibernate多条件组合查询

先看一下客户的数据库表

再看一下实例类Custom

public class Custom {
    private Integer cid;
    private String custName;
    private Dict dict;
    private String custSource;
    private String custPhone;
    private String custMobile;

}

public class Dict {
private Integer did;
private String dName;

}

(get、set方法省略)

我们要做要做的通过客户的custName custSource / dict查询客户集合

我们来看一下DaoImpl的是实现方法

1.拼接sql语句

public List<Custom> query(Custom custom) {
		//拼接字符串
		String hql="from Custom where 1=1 ";
		//创建list集合,存里面查询的参数值
		List<Object> p=new ArrayList<Object>();
		//如果custName不为空,拼接到hql字符串中
		if(custom.getCustName()!=null && !"".equals(custom.getCustName())){
			hql+="and custName=? ";
		//把 ?要传的值设置到list集合中
			p.add(custom.getCustName());
		}
		if(custom.getDict().getDid()!=null){
			hql+="and dict.did=? ";
			p.add(custom.getDict().getDid());
		}
		if(custom.getCustSource()!=null && !"".equals(custom.getCustSource())){
			hql+="and custSource=?";
			p.add(custom.getCustSource());
		}
		//调用hibernate模板的方法实现查询
		return (List<Custom>) this.getHibernateTemplate().find(hql, p.toArray());
		//p.toArray(),让list集合以数组的形式输出
	}

* 注意拼接hql语句时的时候不要忘了前面或后面留空格,不然会报错

2.离线对象查询

public List<Custom> queryForCriteria(Custom custom){
	//创建离线对象,指定对哪个实体类进行操作
	DetachedCriteria criteria = DetachedCriteria.forClass(Custom.class);
	//判断是否为空
	if(custom.getCustName()!=null && !"".equals(custom.getCustName())){
	//对属性设置值
		criteria.add(Restrictions.eq("custName", custom.getCustName()));
	}
	if(custom.getDict().getDid()!=null){
		criteria .add(Restrictions.eq("dict.did", custom.getDict().getDid()));
	}
	if(custom.getCustSource()!=null && !"".equals(custom.getCustSource())){
		criteria.add(Restrictions.eq("custSource", custom.getCustSource()));
	}
	return (List<Custom>) this.getHibernateTemplate().findByCriteria(criteria);
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值