MyBatis批量插入

<insert id="addList" parameterType="java.util.List" useGeneratedKeys="false">
        INTO T_APPLAUD
        (
            ID,
            USER_ID,
            BUSINESS_TYPE,
            PRODUCT_ID,
            CREATE_TIME
        ) VALUES
    <foreach collection="list" item="wdSolr" index="index" separator=",">
            (
            #{item.id, jdbcType=NUMERIC},
            #{item.userId, jdbcType=VARCHAR},
            #{item.businessType, jdbcType=VARCHAR},
            #{item.productId, jdbcType=VARCHAR},
            #{item.createdTime, jdbcType=NUMERIC} 
        )
        </foreach>
    </insert>

代码写的很漂亮,但是效果却没有出现,直接报错:

java.sql.SQLException: ORA-00933: SQL 命令未正确结束

查阅相关资料才知道,Oracle没有这种语法。MySql对上述语法支持。所以需要将SQL做如下修改

<insert id="addList" parameterType="java.util.List" useGeneratedKeys="false">
        INSERT ALL
        <foreach item="item" index="index" collection="list">
        INTO T_APPLAUD
        (
            ID,
            USER_ID,
            BUSINESS_TYPE,
            PRODUCT_ID,
            CREATE_TIME
        ) VALUES
        (
            #{item.id, jdbcType=NUMERIC},
            #{item.userId, jdbcType=VARCHAR},
            #{item.businessType, jdbcType=VARCHAR},
            #{item.productId, jdbcType=VARCHAR},
            #{item.createdTime, jdbcType=NUMERIC} 
        )
        </foreach>
        SELECT 1 FROM DUAL
    </insert>

还有一种方式:

<insert id="addList" parameterType="java.util.List" useGeneratedKeys="false">
        INSERT INTO T_APPLAUD
        (
            ID,
            USER_ID,
            BUSINESS_TYPE,
            PRODUCT_ID,
            CREATE_TIME
        )
        <foreach item="item" index="index" collection="list" separator="union all">
        (
            SELECT 
                #{item.id},
                #{item.userId},
                #{item.businessType},
                #{item.productId},
                #{item.createdTime} 
            FROM DUAL
        )
        </foreach>
    </insert>




posted @ 2019-05-15 11:28  龙X  阅读(319)  评论(0编辑  收藏  举报