Mybatis批量修改联合主键数据

针对需要批量更新包含联合主键的数据库表记录问题,本文分享了一种实用方法。通过使用复杂的SQL更新语句,结合CASE WHEN语句和IN查询,能够有效地处理大批量数据的修改,即使面对存在多个ORGID对应一个EMPID的情况也能确保正确修改。这种方法避免了传统方法在大量数据时的效率瓶颈,提高了数据操作的效率。
摘要由CSDN通过智能技术生成

最近遇上需要批量修改有联合主键的表数据,网上找了很多文章,最终都没找到比较合适的方法,有些只能支持少量数据批量修改,超过十几条就不行了。

最终自己摸索总结了可以批量修改数据方式。

EMPID与ORGID联合主键:

 <update id="updateMoreEmpOrg" parameterType="java.util.List">
        update hr_emp_org
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="ISMAN = CASE " suffix="end,">
                <foreach collection="empOrgList" item="item" index="index">
                    <if test="item.isman != null">
                        when EMPID = #{item.EMPID} and ORGID = #{item.orgid}  then #{item.isman}
                    </if>
                </foreach>
            </trim>
            <trim prefix="UPDATETIME = CASE " suffix="end,">
                <foreach collection="empOrgList" item="item" index="index">
                    <if test="item.updatetime != null">
                        when EMPID = #{item.EMPID} and ORGID = #{item.orgid}  then #{item.updatetime}
                    </if>
                </foreach>
            </trim>

            <trim prefix="hr_status =case " suffix="end,">
                <foreach collection="empOrgList" item="item" index="index">
                    <if test="item.hrStatus != null">
                        when EMPID = #{item.EMPID} and ORGID = #{item.orgid}  then #{item.hrStatus}
                    </if>
                </foreach>
            </trim>
            <trim prefix="hr_rcd =case " suffix="end,">
                <foreach collection="empOrgList" item="item" index="index">
                    <if test="item.hrRcd != null">
                        when EMPID = #{item.EMPID} and ORGID = #{item.orgid}  then #{item.hrRcd}
                    </if>
                </foreach>
            </trim>
        </trim>
        where
        EMPID in
        <foreach collection="empOrgList" item="item" open="(" separator="," close=")">
            #{item.EMPID}
        </foreach>
        and ORGID in
        <foreach collection="empOrgList" item="item" open="(" separator="," close=")">
            #{item.orgid}
        </foreach>
    </update>

直接结果集来两个in查询,这样可以确认在哪些结果集里面进行修改,然而数据可能会出现一个EMPID多个ORG的情况这个时候就不知道具体修改哪条数据了,这个时候我们可以通过when 联合匹配来确定最终修改哪条数据,修改条件中trim里面 case后面不填对比字段,在if里面进行对比判断。最终实现了联合索引里面的修改操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值