码迷,mamicode.com
首页 > 其他好文 > 详细

mybatis批量插入数据

时间:2017-08-09 16:54:32      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:delete   ddl   修改   写法   方法   generated   插入   lis   key   

  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批量插入数据

标签:delete   ddl   修改   写法   方法   generated   插入   lis   key   

原文地址:http://www.cnblogs.com/xujingyang/p/7325885.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!