C/C++教程

MyBatis动态Sql之foreach标签的用法

本文主要是介绍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

这篇关于MyBatis动态Sql之foreach标签的用法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!