**用动态sql实现下图查询
where choose
**
choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。
XML文件
<!-- 动态SQL -->
<select id="find" resultType="com.szt.shop.entity.Goods">
select id,gname,price,unit from goods
<where>
<choose>
<when test="id != null">
id=#{id}
</when>
<when test="gname != null">
gname like CONCAT(CONCAT('%',#{gname},'%'))
</when>
<when test="price != null">
price=#{price}
</when>
<when test="more != null">
price>#{more}
</when>
<when test="less != null">
price<#{less}
</when>
<otherwise>
and unit=#{unit}
</otherwise>
</choose>
</where>
</select>
mapper 层
这里的id不能用int类型,如果查询时用了id之外的任何一个条件,就会出现空指针异常,因为int类型不能是null,我们必须给他一个值。而intege类型默认为null。
List<Goods> find(@Param("id") Integer id,
@Param("gname") String gname,
@Param("price") Double price,
@Param("more") Double more,
@Param("less") Double less,
@Param("unit") String unit);
}
单元测试
查询价格小于10的商品信息
@Test
public void find(){
Integer id=null;
String gname=null;
Double price=null;
Double more=null;
Double less=10.0;
String unit=null;
List<Goods>list=goodsMapper.find(id,gname, price,more,less, unit);
for (Goods goods : list) {
System.err.println(goods);
}
}
价格小于10的商品信息(当然我都测试过,不一一举出)
service
List<Goods> dynamicSql(
Integer id,String gname,Double price,Double more,Double less,String unit);
}
service实现
@Override
public List<Goods> dynamicSql(
Integer id, String gname, Double price, Double more, Double less, String unit) {
return gService.dynamicSql(id, gname, price, more, less, unit);
}
controller
@RequestMapping("sql")
public List<Goods> dynamicSql(Integer id, String gname, Double price, Double more, Double less, String unit){
return gMapper.find(id, gname, price, more, less, unit);
}
页面测试
价格大于8的json数据