1.创建一个Query对象(查询对象)
里面放一些查询的条件,它就是一个JavaBean
创建一个包 cn.itsource.query 和我们的domain在同一级
取名就为XxxQuery -> ProductQuery /TeacherQuery
2.查询的时候需要从前台传入Query对象
List<Product> queryAll(ProductQuery query)
3.mapper的配置是完成高级查询(一定把query传过来)
<where>
<if test="条件是否存在">
and 条件
</if>
</where>
4.前台准备一个查询表单(下例)
<form action="/product" method="post">
名称:<input type="text" name="productName" value="${query.productName}" />
从<input type="number" name="minSalePrice" value="${query.minSalePrice}" >
到<input type="number" name="maxSalePrice" value="${query.maxSalePrice}" >
<input type="submit" value="..查询.." />
</form>
value中是做回显的
注意:所有的name是都Query对象中的属性
5.在Servlet要提收并且封装Query对象(下例)
ProductQuery query = new ProductQuery();
//接收商品名称参数,并且放到query对象
String productName = req.getParameter("productName");
if(isNotBlank(productName)){
query.setProductName(productName);
}
注意:调用的时候要使用传入query的那一个方法
query对象:
package cn.itsource.query;
/**
* 封装商品的查询条件
* */
public class ProductQuery {
//商品名称
private String productName;
//商品最低价格
private Double minSalePrice;
//商品最高价格
private Double maxSalePrice;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Double getMinSalePrice() {
return minSalePrice;
}
public void setMinSalePrice(Double minSalePrice) {
this.minSalePrice = minSalePrice;
}
public Double getMaxSalePrice() {
return maxSalePrice;
}
public void setMaxSalePrice(Double maxSalePrice) {
this.maxSalePrice = maxSalePrice;
}
/**
* 提供一个判断条件方法 用于在对象映射文件中直接使用(${whereSql})
* select * from product ${whereSql}
*
* 动态拼接字符串(sql条件) 第一个条件必须是where开头,后面的必须是and
* 1=1这种方法不是很好。查询效率很低!
* */
/*
public String getWhereSql(){
StringBuffer whereSql = new StringBuffer(" where 1=1 ");
if(productName!=null && !"".equals(productName)){
whereSql.append("and productName like '%").append(productName).append("%'");
}
if(minSalePrice!=null){
whereSql.append("and salePrice >").append(minSalePrice);
}
if(maxSalePrice!=null){
whereSql.append("and salePrice <").append(maxSalePrice);
}
return whereSql.toString();
}
*/
/**
* 第二种方法拼接sql
* */
/*
public String getWhereSql(){
StringBuffer whereSql = new StringBuffer();
if(productName!=null && !"".equals(productName)){
whereSql.append("and productName like '%").append(productName).append("%'");
}
if(minSalePrice!=null){
whereSql.append("and salePrice >").append(minSalePrice);
}
if(maxSalePrice!=null){
whereSql.append("and salePrice <").append(maxSalePrice);
}
//String replaceFirst(String replaceFirst,String replaceMent) 将第一个替换成你想要的 将and替换成where
return whereSql.toString().replaceFirst("and", "where");
}
*/
}
ProductMapper.xml配置文件: