首页 > 代码库 > mybatis批量插入数据

mybatis批量插入数据

  1.先说插入数据到mysql中的mapper.xml写法:

 参数都是list<model>类型

<!--批量插入--><insert id="batchInsertStudent" parameterType="java.util.List">    INSERT INTO STUDENT (id,name,sex,tel,address)    VALUES     <foreach collection="list" item="item" index="index" separator="," >        (#{item.id},#{item.name},#{item.sex},#{item.tel},#{item.address})    </foreach></insert><!--批量删除--><delete id="batchDeleteStudent" parameterType="java.util.List">    DELETE FROM STUDENT WHERE id IN    <foreach collection="list" index="index" item="item" open="(" separator="," close=")">         #{item}     </foreach></delete><!--批量修改--><update id="batchUpdateStudentWithMap" parameterType="java.util.Map" >    UPDATE STUDENT SET name = #{name} WHERE id IN     <foreach collection="idList" index="index" item="item" open="(" separator="," close=")">         #{item}     </foreach></update>

   2.oracle这种做法会报”java.sql.SQLException: ORA-00933: SQL 命令未正确结束“  错误

    正确做法如下:  参数都是list<model>类型

    第一种:使用 insert all into table(...) values(...) into table(...) values(...) select * from dual; 语句来解决     

<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>      

如果还报”java.sql.SQLException: ORA-00933: SQL 命令未正确结束“  错误,原因可能是mybatis批量插入oracle时没有显式指定为 useGeneratedKeys="false" 不然报错~~~

    

    另外一种方法是 insert into table(...) (select ... from dual) union all (select ... from dual)  

<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>

 

mybatis批量插入数据