Mybatis 中传入数组类型参数批量更新表数据的写法

本文介绍了如何在Mybatis中使用数组类型参数进行批量更新表数据的操作。通过提供一个后端JAVA函数及对应的Mybatis SQL语句示例,详细展示了如何根据作者ID、文章ID数组和状态值更新文章状态。同时,前端JS代码部分也展示了如何通过Ajax发送包含文章ID数组的请求,特别提示需要设置`traditional:true`来正确传递数组。

Mybatis 中传入数组类型参数批量更新表数据的写法

假设有个文章表,表字段有:文章ID,状态,作者ID,标题,创建时间。
文章表在 Mybatis 的 xml 文件里的定义:
<resultMap id="BaseResultMap" type="com.test.entity.ArticleEntity" >
    <id column="AUTHORID" property="authorid" jdbcType="INTEGER" />
    <result column="STATE" property="state" jdbcType="TINYINT" />
    <result column="CREATORID" property="creatorid" jdbcType="INTEGER" />
    <result column="TITLE" property="title" jdbcType="VARCHAR" />
    <result column="CRTTIME" property="crttime" jdbcType="TIMESTAMP" />
</resultMap>
  
某作者想删除他的5个文章,传入参数是文章ID的数组、状态值(删除)、作者ID,那么代码写法如下。

后端 JAVA 函数的定义:
int updateBatchStateByPrimaryKeySelective(@Param("arrArticleid") Integer[] arrArticleid, @Param("state") Byte state, @Param("userid") Integer userid);

Mybatis 的 SQL 语句写法:
<update id="updateBatchStateByPrimaryKeySelective">
    update ARTICLE
    set STATE = #{state,jdbcType=TINYINT}
    where AUTHORID in
      <foreach collection="arrArticleid" index="index" item="item" open="(" separator="," close=")">
        #{item,jdbcType=INTEGER}
      </foreach>
    and CREATORID = #{userid,jdbcType=INTEGER}
</update>

前端 JS 代码:
function  deleteSentMails(arrids){
    var  bresult = true;
    $.ajax({
        url: "/com/test/delarticles",
        type: "POST",
        data: {arrArticleid:arrids},
        dataType:"JSON",
        async: false,
        traditional:true,
        success:function(resp){
            if(<成功>){
                bresult =  true;
            }else{
                bresult = false;
            }
        }
    });
     return bresult;
}

注意,需要在 Ajax 中要加上“ traditional:true ”,以支持传送数组的功能。

Ok,完毕!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值