springboot mybatis注解方式批量insert和使用in语句查询

1、批量插入

    @Insert({
            "<script>",
            "insert into sys_user_role(user_id,role_id) values ",
            "<foreach collection='roles' item='item' index='index' separator=','>",
            "(#{item.userId}, #{item.roleId})",
            "</foreach>",
            "</script>"
    })
    int insertByBatch(@Param(value = "roles") List<SysUserRole> roles);

通过@Param指定集合参数,item为集合内每个对象,index为集合自然序号

比较一下用xml文件的方式:

<insert id="insertBatch">
    INSERT INTO 表名( `字段名1`, `字段名2`, `字段...`) VALUES
    <foreach collection="list" item="item" separator="," open="(" close=")">
        #{item.字段1},#{item.字段2},#{item中的每一个字段名...}
    </foreach>
</insert>

 

 

2、使用in语句查询

    @Select({
            "<script>",
            "select count(0) from sys_role where id in ",
            "<foreach collection='roleIds' item='item' index='index' open='(' separator=',' close=')'>",
            "#{item}",
            "</foreach>",
            "</script>"
    })
    Integer checkRoleId(@Param(value = "roleIds") List<Long> roleIds);

查询要特别指定开闭的左右括号

 

比较一下xml文件的用法

    <select id="queryUserByIds" resultMap="SysUserMap">
        select a.id, mobile, username,name, email, a.state, level, company_id,  dept_id,  a.create_time, a.update_time,b.dept_name
        from sys_user a left join sys_dept b on a.dept_id = b.id
        <where>
            <choose>
                <when test="ids !=null and ids.size()>0">
                    a.id in
                    <foreach collection="ids" index="index" separator="," open="(" close=")" item="item">
                        #{item}
                    </foreach>
                </when>
                <otherwise>
                    a.id in ('-1')
                </otherwise>
            </choose>
            <if test="query.name != null and query.name != ''">
                and a.name like concat('%',#{query.name},'%')
            </if>
            <if test="query.deptId != null and query.deptId != ''">
                and a.dept_id = #{query.deptId}
            </if>
        </where>
    </select>

 

posted @ 2020-04-20 20:38  我是属车的  阅读(5875)  评论(0编辑  收藏  举报