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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM