保存两个学生和两个老师,且这两个老师都教了这个两个学生。
Teacher 实体类
package com.yy.domain;
@Setter
@Getter
@ToString
public class Teacher {
private Long id;
private String name;
}
Employee 实体类
package com.yy.domain;
@Setter
@Getter
@ToString
public class Student {
private Long id;
private String name;
// 关联属性
private List
}
注意: Mapper XML 放置的位置是在 resources 目录下。
TeacherMapper 接口
package com.yy.mapper;
public interface TeacherMapper {
void save(Teacher teacher);
}
TeacherMapper.xml 文件
StudentMapper 接口
package com.yy.mapper;
public interface StudentMapper {
void save(Student student);
// 往中间表插入关系数据
void insertRelation(@Param("teacherId")Long teacherId, @Param("studentId")Long studentId);
}
StudentMapper.xml 文件
public class Many2manyTest {
@Test
public void testSave() throws Exception {
Teacher teacher1 = new Teacher();
teacher1.setName("波老师");
Teacher teacher2 = new Teacher();
teacher2.setName("罗老师");
Student s1 = new Student();
s1.setName("小强");
Student s2 = new Student();
s2.setName("小红");
s1.getTeachers().add(teacher1);
s1.getTeachers().add(teacher2);
// s1 被两个老师交了
s2.getTeachers().add(teacher1);
s2.getTeachers().add(teacher2);
// s2 被两个老师交了
SqlSession session = MyBatisUtil.getSession();
TeacherMapper teacherMapper = session.getMapper(TeacherMapper.class);
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
teacherMapper.save(teacher1);
teacherMapper.save(teacher2);
studentMapper.save(s1);
studentMapper.save(s2);
// 往中间表存入数据老师教学生的关系数据
for (Teacher t : s1.getTeachers()) {
studentMapper.insertRelation(t.getId(), s1.getId());
}
for (Teacher t : s2.getTeachers()) {
studentMapper.insertRelation(t.getId(), s2.getId());
}
session.commit();
session.close();
}
}
根据 id 查询学生,并查询其老师。
StudentMapper 接口
package com.yy.mapper;
public interface StudentMapper {
Student get(Long id);
}
StudentMapper.xml 文件
TeacherMapper XML
package com.yy.mapper;
public interface queryByStudentId {
Teacher get(Long id);
}
TeacherMapper.xml 文件
public class Many2oneTest {
@Test
public void testGet() throws Exception {
SqlSession session = MyBatisUtil.getSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Student student = studentMapper.get(2L);
System.out.println(student); session.close();
}
}
以上就是使用 Mybatis 多表实现多对多查询、添加操作了,代码仅供参考,欢迎讨论交流。
手机扫一扫
移动阅读更方便
你可能感兴趣的文章