[{teacherId:001,TeacherName:zhangsan,StudentId:001,StudentName:lisi},{teacherId:001,TeacherName:zhangsan,StudentId:002,StudentName:wangwu}]怎么使用mubatis将上边对象插入老师表和学生表
时间: 2023-11-28 08:51:22 浏览: 78
假设老师表的表名为`teacher_table`,包含`teacher_id`和`teacher_name`两个字段,学生表的表名为`student_table`,包含`student_id`和`student_name`两个字段。
首先,需要定义对应的实体类,以及对应的Mapper接口。这里简化为:
Teacher.java
```java
public class Teacher {
private int teacherId;
private String teacherName;
// getter and setter
}
```
Student.java
```java
public class Student {
private int studentId;
private String studentName;
// getter and setter
}
```
TeacherMapper.java
```java
public interface TeacherMapper {
void insertTeacher(Teacher teacher);
}
```
StudentMapper.java
```java
public interface StudentMapper {
void insertStudent(Student student);
}
```
然后,在MyBatis的配置文件中,定义对应的SQL语句,以及参数的映射。这里可以使用MyBatis的foreach标签,将对象列表中的每个对象都插入到对应的表中。
例如,定义插入老师表的SQL语句:
```xml
<insert id="insertTeacher" parameterType="com.example.Teacher">
insert into teacher_table(teacher_id, teacher_name)
values
<foreach collection="list" item="teacher" separator=",">
(#{teacher.teacherId}, #{teacher.teacherName})
</foreach>
</insert>
```
定义插入学生表的SQL语句:
```xml
<insert id="insertStudent" parameterType="com.example.Student">
insert into student_table(student_id, student_name)
values
<foreach collection="list" item="student" separator=",">
(#{student.studentId}, #{student.studentName})
</foreach>
</insert>
```
最后,在Java代码中,调用Mapper接口的方法即可。假设Mapper接口的实现类为`TeacherMapperImpl`和`StudentMapperImpl`,示例代码如下:
```java
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> map1 = new HashMap<>();
map1.put("teacherId", "001");
map1.put("teacherName", "zhangsan");
map1.put("studentId", "001");
map1.put("studentName", "lisi");
list.add(map1);
Map<String, String> map2 = new HashMap<>();
map2.put("teacherId", "001");
map2.put("teacherName", "zhangsan");
map2.put("studentId", "002");
map2.put("studentName", "wangwu");
list.add(map2);
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper teacherMapper = sqlSession.getMapper(TeacherMapper.class);
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
List<Teacher> teachers = new ArrayList<>();
List<Student> students = new ArrayList<>();
for (Map<String, String> map : list) {
Teacher teacher = new Teacher();
teacher.setTeacherId(Integer.parseInt(map.get("teacherId")));
teacher.setTeacherName(map.get("teacherName"));
teachers.add(teacher);
Student student = new Student();
student.setStudentId(Integer.parseInt(map.get("studentId")));
student.setStudentName(map.get("studentName"));
students.add(student);
}
teacherMapper.insertTeacher(teachers);
studentMapper.insertStudent(students);
sqlSession.commit();
sqlSession.close();
```
以上代码中,首先将原始的列表转换为`Teacher`和`Student`对象的列表,然后调用对应的Mapper接口方法,将数据插入到数据库中。
需要注意的是,这里示例代码中使用了MyBatis的工具类`MybatisUtils`来获取SqlSession对象。此外,还需要在MyBatis的配置文件中,定义对应的数据源和Mapper接口扫描路径。
阅读全文