MyBatis动态Sql之foreach标签的用法

  1. mysql 数据库—> foreach 实现批量插入
/**
 * 批量插入用户信息
 *
 * @param userList
 * @return
 */
int insertList(List<SysUser> userList);
<insert id="insertList" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO sys_user(user_name, user_password, user_email, user_info, head_img, create_time)
    VALUES
    <foreach collection="list" item="user" separator=",">
        (#{user.userName},#{user.userPassword},#{user.userEmail},#{user.userInfo},#{user.headImg,jdbcType=BLOB},#{user.createTime,jdbcType=TIMESTAMP})
    </foreach>
</insert>
  1. oracle 数据库—>foreach 实现批量插入
    当用如上写法时,报Cause: java.sql.SQLSyntaxErrorException: ORA-00933: SQL 命令未正确结束
    正确示例:
<insert id="myInsert" parameterType="java.util.List">
        insert into NST_EXPRESS_HOLIDAY(ID,NAME)
        select A.ID,A.NAME from (
        <foreach collection="list" item="one" index="index" separator="UNION ALL">
          SELECT
            #{one.id} ID,
            #{one.name} NAME
            FROM dual
        </foreach>
        ) A
    </insert>

参考资料1
参考资料2

上一篇:list stream().forEach


下一篇:迭代器iterator接口