MyBatis 小 tips(一)一个字符串代表多个参数的解决方案(codeOrName)
Contents
有个接口文档的要求:查询当前库存(可根据商品类别、商品编码或者名称搜索),如下:
请求参数:Integer page, Integer rows, String codeOrName, Integer goodsTypeId
请求方式:POST
返回值类型: JSON
返回值:Map<String,Object>根据这个传入参数,可以把controller定义成下面这样:
@RestController
@RequestMapping("/goods")
public class GoodsController {
@Resource
private GoodsService goodsService;
// 首页默认: 当前库存查询
@PostMapping("/listInventory")
public Map<String, Object> listInventory(Integer page,
Integer rows,
String codeOrName,
Integer goodsTypeId) {
return goodsService.findListInventory(page, rows, codeOrName, goodsTypeId);
}
}可以看到,其他参数还好,但是编码和名称是用的codeOrName这一个字符串来传入的。那么这时候 MyBatis 的语句应该怎么编写呢?
可以像下面这样:
<select id="selectListInventory" resultMap="listInventoryMap">
...
...
<where>
<if test="codeOrName != null and codeOrName != ''">
and (t_goods.goods_code = #{codeOrName} or t_goods.goods_name like "%"#{codeOrName}"%")
</if>
<if test="goodsTypeId != null and goodsTypeId != ''">
and (t_goods.goods_type_id = #{goodsTypeId})
</if>
</where>
...
...
</select>