-
批量查询
<select id="selectGoods" parameterType="cn.com.xxx.xx.entity.Goods" resultMap="goodsResultMap"> select g.GOODS_ID, g.GOODS_NAME, g.GOODS_CODE, g.GOODS_DATE, g.GOODS_STATE, g.GOODS_NUM_STOCK, g.GOODS_PRICE, g.GOODS_BRAND, g.GOODS_TEL, gd.GOODS_DICTIONARY_NAME, gd.GOODS_DICTIONARY_CODE, gd.GOODS_DICTIONARY_PCODE, gd.GOODS_DICTIONARY_TYPE, gt.TREE_CODE, gt.TREE_PARENT_CODE, gt.TREE_NAME from goods_info g left join goods_dictionary gd on g.GOODS_CODE = gd.GOODS_DICTIONARY_CODE left join goods_tree gt on g.GOODS_TREE_CODE = gt.TREE_CODE <where> <if test="goodsName!=null and goodsName != ''"> AND g.GOODS_NAME like CONCAT('%',#{goodsName},'%') </if> <if test="treeCodeList!= null and treeCodeList.size() > 0"> AND g.GOODS_TREE_CODE in <foreach collection="treeCodeList" open="(" close=")" separator="," item="treeCode"> #{treeCode} </foreach> </if> </where> ORDER BY GOODS_NAME </select>
- 注意
foreach
标签中collection
指向的是传来的集合参数名,item
后就是接下来操作的每一个集合元素 - 在是否为空的判断中:
<if test="treeCodeList!= null">
只用不等于 null 不够严谨,建议再加上.size > 0
或.isEmpty()
(更直观)
- 注意
-
批量删除同理:
<delete id="deleteSomeGoodsByIds" parameterType="list" > delete from goods_info where GOODS_ID in <foreach collection="list" open="(" close=")" separator="," item="id"> #{id} </foreach> </delete>
-
提一嘴:
- 前端传来集合为空:两种方式都不会报错(集合就相当于:
List<String> emptyList = new ArrayList<>();
只实例化但不包含任何元素) - 后端指定集合为 null:两种方式都会抛出
NullPointerException
异常,所以一般搭配!=null
做一个额外的检查 - 但 mapper 不会,mapper 里的动态 sql 会自动处理这种 NullPointerException 空指针异常并判断为 false,但最好还是指明
- 前端传来集合为空:两种方式都不会报错(集合就相当于:
-
再提一嘴(仅供参考):
- sql 语句时建议 ——> 单一范围用 like + %,小指定范围用 between xx and xx,大范围用 in(xx)