前言
在近期的项目中引入了 shardingSphere 分库分表,排查过后发现失败的原因是分库分表字段未匹配。
我们举个栗子,我们这边分库分表的字段为 projectId。正常来说只要有传入 projectId 作为查询条件shardingsphere
中的拦截器会自动去根据我们的分库分表规则进行拼接新的sql语句。但实际上根据测试结果所得发现只有在第一次foreach时才会根据分库分表规则进行对sql进行自动拼接。
错误如下图代码所示:
<update id="updateBatch">
<foreach collection="updateList" item="item" index="index" separator=";">
update
b_bank_book_account
set
bank_abbreviation = #{item.bankAbbreviation},
bank_full_name = #{item.bankFullName},
bank_account = #{item.bankAccount},
account_nature = #{item.accountNature},
interest_rate = #{item.interestRate},
<if test="updater != null">
update_user_name = #{updater.userName},
update_full_name = #{updater.fullName},
</if>
update_time = unix_timestamp(now())*1000
where id = #{item.id} and project_id = #{item.projectId}
</foreach>
</update>
我们希望得到的每一次的表名都为 update b_bank_book_account_0
但实际上得到的结果只有第一次是 update b_bank_book_account_0
从第二次开始还是 update b_bank_book_account
并没有进行转换。
该如何解决这个问题呢?那就只能曲线救国了。
在接口外通过分库分表键于规则计算好之后在第二次循环时手动拼接了。下附解决代码。
${strategy}
为计算后分表规则
<update id="updateBatch">
<foreach collection="updateList" item="item" index="index" separator=";">
update
<if test="index == 0">
b_bank_book_account
</if>
<if test="index != 0">
b_bank_book_account_${strategy}
</if>
set
bank_abbreviation = #{item.bankAbbreviation},
bank_full_name = #{item.bankFullName},
bank_account = #{item.bankAccount},
account_nature = #{item.accountNature},
interest_rate = #{item.interestRate},
<if test="updater != null">
update_user_name = #{updater.userName},
update_full_name = #{updater.fullName},
</if>
update_time = unix_timestamp(now())*1000
where id = #{item.id} and project_id = #{item.projectId}
</foreach>
</update>
本文由 SoGeek_Studio 发布,有任何问题请留言评论,欢迎指正。