mybatis如何实现批量更新和插⼊新增实例详解(附SQL以及mapper配置)Mybatis批量插⼊、批量修改
批量插⼊
step1:创建DB表
CREATE TABLE`student_info`(
`STUDENT_ID`BIGINT(20)NOT NULL AUTO_INCREMENT UNIQUE COMMENT'学⽣id',
`STUDENT_NAME`VARCHAR(30)NOT NULL COMMENT'学⽣姓名',
`STUDENT_AGE`INTEGER(11)DEFAULT1COMMENT'学⽣年龄',
`CREATE_TIME`TIMESTAMP(6)NULL DEFAULT now()COMMENT'创建时间',
`UPDATE_TIME`TIMESTAMP(6)NULL DEFAULT now()COMMENT'修改时间',
PRIMARY KEY(`STUDENT_ID`)
)ENGINE=InnoDB
CHARACTER SET'utf8'COLLATE'utf8_general_ci';
step2:编写l⽂件
<insert id="batchInsert"useGeneratedKeys="true"parameterType="java.util.List">
<selectKey resultType="long"keyProperty="studentId"order="AFTER">
SELECT
LAST_INSERT_ID()
</selectKey>
INSERT INTO student_info(STUDENT_NAME, STUDENT_AGE, CREATE_TIME, UPDATE_TIME)
VALUES
<foreach collection="list" item="data" separator="," index = "index">
(#{data.studentName},#{data.studentAge},#{ateTime},#{data.updateTime})
</foreach>
</insert>
step3:java代码简单⽰例
List<StudentInfo> list =new ArrayList<StudentInfo>();
StudentInfo info =new StudentInfo();
info.setStudentName("张三丰");
info.setStudentAge(149);
info.setCreateTime(new Date());
info.setUpdateTime(new Date());
list.add(info);
StudentInfo info2 =new StudentInfo();
info.setStudentName("孙中⼭");
info.setStudentAge(59);
info.setCreateTime(new Date());
info.setUpdateTime(new Date());
list.add(info2);
StudentInfo info3 =new StudentInfo();
info.setStudentName("王才⼒");
info.setStudentAge(33);
info.setCreateTime(new Date());
info.setUpdateTime(new Date());
list.add(info3);
int batchExec = studentInfoMapper.batchInsert(list);
批量修改
step1: 延⽤学⽣信息表,写sql
<update id="batchUpdate"parameterType="java.util.List">
update student_info
<trim prefix="set"suffixOverrides=",">
<trim prefix="STUDENT_NAME =case"suffix="end,">
<foreach collection="list"item="i"index="index">
<if test="i.studentName!=null">
when STUDENT_ID=#{i.studentId}  then
#{i.studentName}
</if>
</foreach>
</trim>
<trim prefix=" STUDENT_AGE =case"suffix="end,">
<foreach collection="list"item="i"index="index">
<if test="i.studentAge!=null">
when STUDENT_ID=#{i.studentId} then
批量更新sql语句#{i.studentAge}
</if>
</foreach>
</trim>
</trim>
</update>
修改的语句相当于多次执⾏
<!--mybatis中批量执⾏uodate操作⽬前只能如此,若读者有新发现可留⾔告知-->
update student_info set STUDENT_NAME = case when STUDENT_ID=#{i.studentId}  then #{i.studentName} step2:java⽰例code
List<StudentInfo> handlerList =new ArrayList<StudentInfo>();
for( StudentInfo innerInfo : list  ){
StudentInfo record =new StudentInfo();
record.StudentId());
StudentId()==1){
record.StudentName()+"⼗年前");
record.StudentAge()-10);
}else{
record.StudentName()+"五年前");
record.StudentAge()-5);
}
handlerList.add(record);
}
int exec = studentInfoMapper.batchUpdate(handlerList);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。