mybatis中的foreach

动态 SQL 的另一个常见使用场景是对集合进行遍历,foreach几个属性:

1》collection:指定要遍历的集合:传入的如果是list没有使用@Param注解,则可以填list

用了注解@Param("ids"):

public List<Emp> selectEmps(@Param("ids")List<Integer> ids);
 <select id="selectEmps" resultType="com.mybatis.bean.Emp">
        select
        id,
        name,
        gender,
        email
        from emp where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </select>

没有用注解@Param("xx"):

public List<Emp> selectEmps(List<Integer> ids);
<select id="selectEmps" resultType="com.mybatis.bean.Emp">
        select
        id,
        name,
        gender,
        email
        from emp where id in
        <foreach collection="list" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </select>

2》item:将当前遍历出的元素赋值给指定的变量
3》separator:每个元素之间的分隔符
4》open:遍历出所有结果拼接一个开始的字符
5》close:遍历出所有结果拼接一个结束的字符
6》index:索引。遍历list的时候是index就是索引,item就是当前值;遍历map的时候index表示的就是map的key,item就是map的值
#{变量名}就能取出变量的值也就是当前遍历出的元素,如果是基本数据类型,则就是item里面的变量;

如果是对象如emp,要传入id值,item里面的变量是emp,则是emp.id

posted @ 2020-04-21 21:36  来一杯可乐  阅读(279)  评论(0编辑  收藏  举报