MyBatis中foreach动态SQL

MyBatis中foreach动态SQL

查询条件是list时,或者根据条件批量更新时,需要使用foreach动态SQL。
例如:
在这里插入图片描述
在这里插入图片描述
item: 集合项,如果集合里是基础数据类型,就用#{item};如果集合里是对象,就用#{item.属性}。注意区分。
separator: 迭代分隔符。
图一传逗号:separator="," 效果如下:
SELECT * FROM product_category WHERE category_type IN (item1,item2,item3,item4,item5)
图二传分号:separator=";" 效果如下:
UPDATE buss_store SET state = #{item.state} WHERE id = #{item.id};
UPDATE buss_store SET state = #{item.state} WHERE id = #{item.id};
UPDATE buss_store SET state = #{item.state} WHERE id = #{item.id};

参考文档:

https://mybatis.org/mybatis-3/zh/dynamic-sql.html

MyBatis对比MyBatis-plus

场景
Product_info表中有category_type字段(int类型) 实体类ProductInfo
Product_category表中有category_type字段(int类型) 实体类ProductCategory
需要从Product_info中取出一组category_type,存放在list中,并且将此list作为条件,去Product_category中查询记录。

使用MyBatis实现
1.xml
在这里插入图片描述
2.mapper
在这里插入图片描述
3.测试
在这里插入图片描述
使用MyBatis-plus实现
1.mapper
在这里插入图片描述
2.测试
由于条件是int类型的集合,我们使用MyBatis-plus自带的方法selectList(Wrapper wrapper)。Warpper为条件构造器
在这里插入图片描述
查询结果相同。可以看到,此场景使用MyBatis查询时,需要编写mapper.xml,手动编写SQL语句,编写对应mapper接口。而使用MyBatis-plus时,只需要在mapper接口中继承BaseMapper接口,无需手动编写SQL和mapper,利用条件构造器selectList(Wrapper wrapper)即可。

Mybatis-plus: https://mybatis.plus/guide/wrapper.html