主类
/**
* 多条件动态查询
*/
@Test
public void selByConditions() {//通过条件查找,实现多条件查找
Configuration cfg = null;
SessionFactory sf = null;
Session session = null;
EmpCondition condition = new EmpCondition();
condition.setJob("CLERK");
condition.setSalary(1000d);
condition.setBeginDate(DateUtils.string2Date("1981-04-01"));
condition.setEndDate(DateUtils.string2Date("1985-09-09"));
String hql = "from Emp where 1=1";
if (condition.getJob() != null) {
hql += " and job=:job";//命名参数
}
if (condition.getSalary() != null) {
hql += " and sal>:salary";
}
if (condition.getBeginDate() != null) {
hql += " and hiredate>=:beginDate";
}
if (condition.getEndDate() != null) {
hql += " and hiredate<=:endDate";
}
try {
cfg = new Configuration().configure();
sf = cfg.buildSessionFactory();
session = sf.openSession();
Query query = session.createQuery(hql);
query.setProperties(condition);// 以下注释代码,就是此方法的底层实现
// if(condition.getJob()!=null){
// query.setParameter("job", condition.getJob());
//
// }
//
// if(condition.getSalary()!=null){
// hql+=" and sal=:salary";
// }
//
// if(condition.getBeginDate()!=null){
// hql+=" and hiredate>=:beginDate";
// }
//
// if(condition.getEndDate()!=null){
// hql+=" and hiredate<=:endDate";
// }
List<Emp> list = query.list();
for (Emp emp : list) {
System.out.println(emp.getEname() + "*****" + emp.getJob());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (session != null && session.isOpen()) {
session.close();// 游离状态:数据库中存在,session中不存在
}
}
工具类:DateUtils.java
package com.yh.hib.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtils {
public static Date string2Date(String str) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(str);//string 类型转换为date类型
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
查询条件实体类:EmpCondition.java
package com.yh.hib.entity;
import java.util.Date;
public class EmpCondition {
private String job;
private Double salary;
private Date beginDate;
private Date endDate;
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public Date getBeginDate() {
return beginDate;
}
public void setBeginDate(Date beginDate) {
this.beginDate = beginDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
}