mybatis 之 sql语句写法集锦
1、mapper接口中的方法存在批量数据操作,接口参数是List类型
在mybatis的 xml 文件中,使用 foreach 动态标签拼接 SQL 语句,每一条数据的更新语句对应一条update语句,多条语句最终使用";"号进 行拼接
<update id="updateBatchById">
<foreach collection="list" item="item" separator=";">
update
`t_student`
set
`name` = #{item.name},
`age` = #{item.age}
where
id = #{item.id}
</foreach>
</update>
说明:其中 "list" 是接口参数类型为List的参数变量名;"item" 是List中的每个项,临时变量名;
执行下来之后,多个sql语句是以;拼接的,如: update xxxxx;update xxxx;update xxxx;
但存在部分数据库不支持多个sql语句一起执行,使用 ;隔开的方式,此时可以通过在数据库连接URL中指定allowMultiQueries参数值为true告诉数据库以支持”;"号分隔的多条语句的执行。
2、批量更新,使用 foreach 更新,加入 <set> 和 <if> 标签判断与设置
<update id="updatePrice">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update price_info
<set>
<if test="item.status != null and item.status != ''">
status = #{item.status},
</if>
<if test="item.price != null and item.price != ''">
price = #{item.price},
</if>
</set>
where id = #{item.id}
</foreach>
</update>
PS:只有string类型的数据才能使用 xxx != ' ' 当其他类型使用就会报类型转换错误

浙公网安备 33010602011771号