确定对员工名称进行模糊查询,对工资进行范围查询。
1.创建query包,在包中创建EmployeeQueryObject类.
2.类中定义查询关键字,最低工资,最高工资.
private String name;//模糊查询的关键字
private BigDecimal minSalary;//最低工资
private BigDecimal maxSalary;//最高工资
3.提供该三属性的getter,setter方法.
4.定义条件(conditions)以及参数(params)两个list集合.
private List<String> conditions = new ArrayList<>();
private List<Object> params = new ArrayList<>();
5.自定义方法,getQuery()以及getParameters()以及一个判断方法hasLength(String str).在getQuery()方法中,判断如果查询关键字name有值,如果最低工资不为空,如果最高工资不为空,进行如下操作.getParameters()方法中设置占位符参数,返回参数集合对象.haslength方法中进行基本操作.
return str!=null&&!"".equals(str.trim())
public String getQuery(){
if (hasLength(name)){
conditions.add("name like ?");
params.add("%"+name+"%");
}
if (minSalary != null){
conditions.add("salary >= ?");
params.add(minSalary);
}
if (maxSalary != null){
conditions.add("salary <= ?");
params.add(maxSalary);
}
if (conditions.size()==0){
return "";
}
return " where "+ StringUtils.join(conditions," and ");
}
//设置占位符参数
public List<Object> getParameters(){
return params;
}
public boolean hasLength(String str){
return str != null && !"".equals(str.trim());
}
6.dao类中定义query方法.
List<Employee> query(EmployeeQueryObject qo);
7.对应dao实现类(impl)中实现query方法.
public List<Employee> query(EmployeeQueryObject qo) {
String sql = "select * from t_employee"+ qo.getQuery();
System.out.println("sql语句:"+sql);
System.out.println("参数:"+qo.getParameters());
return JdbcTemplate.query(sql,new BeanListHandler<Employee>(Employee.class),qo.getParameters().toArray());
}
8.action中员工列表方法中
//列表
public String execute() throws Exception {
ActionContext.getContext().put("employees",dao.query(qo));
return LIST;
}
9.测试类.
@Test
public void query() {
EmployeeQueryObject qo = new EmployeeQueryObject();
qo.setName("test");
qo.setMinSalary(new BigDecimal("1000"));
qo.setMaxSalary(new BigDecimal("1200"));
List<Employee> list = dao.query(qo);
for (Employee e : list) {
System.out.println(e);
}
}
10.employee_list.jsp中.
<s:form namespace="/" action="employee">
名称:<s:textfield name="qo.name"/>
工资:<s:textfield name="qo.minSalary"/>
到<s:textfield name="qo.maxSalary"/>
<s:submit value="查询"/>
至此简单的高级查询就结束了.