[{teacherId:null,TeacherName:zhangsan,StudentId:001,StudentName:lisi},{teacherId:null,TeacherName:zhangsan,StudentId:002,StudentName:wangwu}]怎么使用mybatis将上边对象批量插入老师表获取插入id之后再批量学生表关联该id
时间: 2023-11-28 10:51:28 浏览: 47
Mybatis数据批量插入如何实现
可以使用MyBatis的批量插入功能和返回主键值的功能来实现。
首先,在Mapper中定义两个方法,一个用于批量插入老师,另一个用于批量插入学生。老师表需要返回主键值,所以使用useGeneratedKeys和keyProperty来指定返回主键值的属性名。
```
public interface TeacherMapper {
@Insert({
"<script>",
"insert into teacher(TeacherName) values ",
"<foreach collection='list' item='item' index='index' separator=','>",
"(#{item.teacherName})",
"</foreach>",
"</script>"
})
@Options(useGeneratedKeys = true, keyProperty = "teacherId")
void batchInsertTeacher(List<Teacher> teacherList);
@Insert({
"<script>",
"insert into student(TeacherId, StudentName) values ",
"<foreach collection='list' item='item' index='index' separator=','>",
"(#{item.teacherId}, #{item.studentName})",
"</foreach>",
"</script>"
})
void batchInsertStudent(List<Student> studentList);
}
```
然后,在Service中调用这两个方法。首先调用batchInsertTeacher方法批量插入老师表,然后获取插入的主键值,再将主键值设置给对应的学生对象,最后调用batchInsertStudent方法批量插入学生表。
```
@Service
public class TeacherStudentService {
@Autowired
private TeacherMapper teacherMapper;
@Autowired
private StudentMapper studentMapper;
public void batchInsert(List<Teacher> teacherList, List<Student> studentList) {
// 批量插入老师表
teacherMapper.batchInsertTeacher(teacherList);
// 获取插入的主键值
for (int i = 0; i < teacherList.size(); i++) {
teacherList.get(i).setTeacherId(teacherMapper.selectKey());
}
// 批量插入学生表
studentMapper.batchInsertStudent(studentList);
}
}
```
阅读全文