最近在项目中用到到sharding-sphere分表,为了提高程序运行效率采用了批量更新的sql拼接方式,如下图
<update id="batchUpdate">
<foreach collection="list" item="item" separator=";">
update test
set name= #{item.name}
where id= #{item.id}
</foreach>
</update>
其中,test分了4张表(test0、test1、test2、test3),运行程序发现出现异常,打印出来的sql如下:
update test2 set name='wukong' where id=5;
update test set name='shaseng' where id=6;
update test set name='tangseng' where id=7;
update test set name='bajie' where id=8;
从日志可以看到,只有第一条sql确定了分表的具体表明,for循环中的剩余3条没有确定表名,查看各方资料,发现sharding-sphere目前不支持这种批量更新。
既然具体的表名不能由sharding-sphere生成,那么只能我们自己来确定,可以通过在后端根据分表算法获取到,然后通过${具体表明}的方式传入到sql中进行组装,这样就可以跳过sharding-sphere这种缺陷。
解决方法:
<update id="batchUpdate">
<foreach collection="list" item="item" separator=";">
update ${tableName}
set name= #{item.name}
where id= #{item.id}
</foreach>
</update>