//需要保证Emp和EmpProperties中的setter和getter以及属性以及 参数占位符(:eName) 的一致
//动态查询
@Test
public void test4(){
EmpProperties ep=new EmpProperties();
//set query conditions
ep.seteName("%A%");
ep.setStartDate(new Date(383155200000L));
ep.setEndDate(new Date());
ep.setJob("CLERK");
//1.obtain org.hibernate.Session object.
Session ss=HibernateUtil.getSession();
//2.hql statement: s
StringBuffer hql=new StringBuffer("from Emp e where 1=1 ");
//3.判断EmpProperties总属性是否为null
if(ep.geteName()!=null){
hql.append(" and e.eName like :eName ");//e.eName和Emp中的属性保持一致|:eName和EmpProperties中的属性保持一致
}
if(ep.getStartDate()!=null){
hql.append(" and e.hireDate>=:startDate ");
}
if(ep.getEndDate()!=null){
hql.append(" and e.hireDate<=:endDate ");
}
if(ep.getJob()!=null){
hql.append(" and e.job=:job");
}
//执行hql语句,hql转换为String(使用toString()方法)
Query qr=ss.createQuery(hql.toString());
//给hql语句中的参数赋值
qr.setProperties(ep);
@SuppressWarnings("unchecked")
List<Emp> el= qr.list();
for (Emp emp : el) {
System.out.println(emp.geteName()+"\t"+ emp.getEmpNo());
}
System.out.println("查询记录数: "+el.size());
HibernateUtil.closeResource(ss);
}