先看一下客户的数据库表
再看一下实例类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);
}