mybatis 批量插入/批量修改/批量删除

  • Mybatis批量操作

Mybatis批量操作

1、批量新增
int batchSaveBook(@Param("bookList")List bookList);
<insert id="batchSaveBook" parameterType="java.util.List">
        insert into book (`name`, user_id,
        price)
        values
        <foreach collection="bookList" item="book" separator=",">
            ( #{book.name,jdbcType=VARCHAR}, #{book.user_id,jdbcType=INTEGER},
            #{book.price,jdbcType=DOUBLE})
        foreach>
insert>

2、批量修改

批量修改注意在Mysql连接后面添加&allowMultiQueries=true不然会报错

int batchUpdateBook(@Param("list") List bookList);
<update id="batchUpdateBook" parameterType="java.util.List">
        <foreach collection="list" item="book" open="" close="" separator=";">
            update book
            <set>
                <if test="book.name!=null">
                    `name`=#{
     book.name,jdbcType=VARCHAR},
                </if>
                <if test="book.user_id!=null">
                    user_id = #{
     book.user_id,jdbcType=INTEGER},
                </if>
                <if test="book.price!=null">
                    price = #{
     book.price,jdbcType=DOUBLE}
                </if>
            </set>
            where id=#{
     book.id,jdbcType=INTEGER}
        </foreach>
</update>

4、批量删除

int batchDelete(@Param("list")List ids);
<delete id="batchDelete" parameterType="java.util.List">
    delete from book where id IN
    <foreach collection="list"  item="ids" open="(" separator="," close=")"  >
      #{ids}
    foreach>
delete>

你可能感兴趣的:(mybatis,mybatis)