批量向数据库插入数据
如何批量insert呢?废话不多说直接上代码!记的给俺点个赞。
在mapper.xml中的配置
<insert id="insertStudentList" parameterType="st.domain.student" useGeneratedKeys="true" keyProperty="id">
insert into student
<trim prefix="(" suffix=")" suffixOverrides=",">
id,
name,
age
</trim>
values
<foreach collection="studentList" item="item" index="index" separator=",">
(
#{item.id},
#{item.name},
#{item.age}
)
</foreach>
</insert>
在mapper接口中写法
public int insertStudentList(@Param("studentList") List<student> studentList);
在service中的写法
@Autowired
private StudentMapper studentMapper;
public void addTestDeviceRecord(){
Student student= new Student();
List<Student> students = new ArrayList<>();
for(int i=i;i<100;i++){
student.setName("张"+i);
student.id(i*i);
student.age(i);
students.add(student);
}
long start = System.currentTimeMillis();
if (CollectionUtils.isNotEmpty(students)){
studentMapper.insertStudentList(students);
}
log.info("批量插入用了秒"+(System.currentTimeMillis() - start));
}
都看到这要不关注下吧!🤭🤭