文章目录
前言
前面介绍了多对一的案例,在这里我们将进行一对多的案例演示
一、一对多是什么?
一对多关系是指在两个实体之间建立的一种关系,其中一个实体可以与多个另一个实体相关联,而另一个实体只能与一个该实体相关联。例如,一个班级有多个学生,但每个学生只属于一个班级,这就是一对多关系。
二、使用步骤
1.创建实体类
@Data
public class Student {
private int id;
private String name;
private int tid;
}
@Data
public class Teacher {
private int id;
private String name;
//一个老师教多个学生
List<Student> students;
}
2.创建mapper接口
public interface TeacherMapper {
//获取指定老师下的所有学生
Teacher getTeachers(@Param( "id" ) int id);
Teacher getTeachers2(@Param( "id" ) int id);
}
3.创建mapper.xml文件
<select id="getTeachers" resultMap="TeacherAndStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.tid=t.id and t.id=#{id}
</select>
<resultMap id="TeacherAndStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
第二种
<select id="getTeachers2" resultMap="TeacherAndStudent2">
select * from teacher where id=#{id}
</select>
<resultMap id="TeacherAndStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid=#{tid}
</select>
4.绑定mapper接口
<!-- 接口绑定-->
<mappers>
<mapper resource="com/RXJ/mapper/StudentMapper.xml"/>
<mapper resource="com/RXJ/mapper/TeacherMapper.xml"/>
</mappers>
5.测试
@Test
public void teacherTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper( TeacherMapper.class );
Teacher teachers = mapper.getTeachers( 1 );
System.out.println(teachers.toString());
sqlSession.close();
}
//第二种的测试
@Test
public void teacherTest1(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper( TeacherMapper.class );
Teacher teachers = mapper.getTeachers2( 1 );
System.out.println(teachers.toString());
sqlSession.close();
}
总结:
以上就是一对多案例的全部内容,本文仅仅简单介绍了一对多,目的是为了让小白更好更快的理解一对多的概念及其使用。