Mybatis提供了<foreach>来实现SQL语句中的批量操作,例如,批量删除与批量插入。其中具体的参数可以通过实例来说明。
批量插入:
<insert id="insertBatch">
insert into student (name, img, sex, create_time)
values
<foreach collection="studentList" item="student" separator=",">
(
#{student.name,jdbcType=VARCHAR},
#{student.img,jdbcType=VARCHAR},
#{student.sex,jdbcType=INTEGER},
#{student.createTime,jdbcType=TIMESTAMP}
)
</foreach>
</insert>
<foreach>标签中额参数:
collection表示出入的对象的类型,有list,array和map类型。
item是给对象中每一项的别名。
separator是每一项的间隔内容。
index在传参是list和数组时,index是元素的序号,传参map时,index是元素的key。可选传参数。
opean和close分别表示<foreach>要构造的内容的起始和结尾。例如在下面的批量删除中是左右括号。该参数可选传,可以保证SQL语句的正确。
<delete id="deleteByIds" parameterType="java.lang.Long" >
delete from student where id in
<foreach collection="idList" index="index" item="item"
open="(" separator="," close=")">
#{item}
</foreach>
</delete>