在mybatis中可以使用foreach标签做批量插入和更新操作,以批量插入为例:
<insert id="insertMsg" parameterType="xz.hr.domain.ResumeMessage">INSERT INTO hr_resume_message (id,content,accept_user,create_by,create_date)
VALUES <foreach collection="ids" item="id" separator="," index="index"> (#{id} #{content}, #{id}, #{createBy}, sysdate) </foreach> </insert>
collection属性填写参数中对应的集合变量,我这里是实体中的ids属性为一个集合。
需要注意的是,oracle数据的写法不一样,它不支持 insert tableName (id,name) values (xx,xx),(xx,xx)写法,正确的姿势如下:
1.需要取掉values
2.separator 要改为union all
3.foreach标签中没有括号
4.另外如果是使用序列写法也要变,要把序列单独拿出来,否则要报错:
//不使用序列 <insert id="save" parameterType="UserRole"> insert into sys_user_role (user_id, role_id) <foreach collection="roleIdList" item="item" index="index" separator="UNION ALL" > SELECT #{userId}, #{item} FROM dual </foreach> </insert>
//使用序列
<insert id="insertMsg" parameterType="xz.hr.domain.ResumeMessage"> INSERT INTO hr_resume_message (id,content,accept_user,create_by,create_date) SELECT HR_PUB_SEQ.nextval,A.* from ( <foreach collection="ids" item="id" separator="UNION ALL" index="index"> SELECT #{content}, #{id}, #{createBy}, sysdate FROM DUAL </foreach> ) A </insert>