概念:
一个老师拥有多个学生
步骤:
按结果嵌套查询:
- 创建实体类
Student
import lombok.Data;
/**
* @author jitwxs
* @date 2021年04月03日 13:45
*/
@Data
public class Student {
private int id;
private String name;
//学生关联一个老师
private int tid;
}
Teacher
import lombok.Data;
import java.util.List;
/**
* @author jitwxs
* @date 2021年04月03日 13:44
*/
@Data
public class Teacher {
private int id;
private String name;
private List<Student> studentList;
}
- 编写接口
import org.apache.ibatis.annotations.Param;
import pojo.Teacher;
public interface TeacherMapper {
//获取老师
// List<Teacher> getTeacher();
//获取指定老师下的学生及其老师的信息
Teacher getTeacher(@Param("id")int id);
}
- 编写配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的dao借口/mapper接口-->
<mapper namespace="dao.TeacherMapper">
<select id="getTeacher" resultMap="TeacherStudent" >
SELECT t.id tid,t.name tname,s.id sid,s.name sname FROM teacher t LEFT JOIN student s ON t.id=s.`tid` WHERE t.id=#{id};
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--复杂的属性单独处理
association:对象
collection:集合
javatype:指定属性的类型
offType:获取集合中的泛型信息
-->
<collection property="studentList" ofType="Student">
<result property="id" column="sid" />
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
</mapper>
- 测试
public class Test {
@org.junit.Test
public void test(){
SqlSession sqlSession= MyBatisUtils.getSqlSession();
TeacherMapper teacherMapper=sqlSession.getMapper(TeacherMapper.class);
Teacher teachers=teacherMapper.getTeacher(1);
System.out.println(teachers);
sqlSession.close();
}
}
按照查询嵌套查询:
- 编写接口
Teacher getTeacher2(@Param("id")int id);
- 编写配置文件
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id=#{id}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="studentList" javaType="ArrayList" ofType="student" select="getStudent" column="id"/>
</resultMap>
<select id="getStudent" resultType="Student">
select * from student where tid=#{tid}
</select>
- 测试
public class Test {
@org.junit.Test
public void test(){
SqlSession sqlSession= MyBatisUtils.getSqlSession();
TeacherMapper teacherMapper=sqlSession.getMapper(TeacherMapper.class);
Teacher teachers=teacherMapper.getTeacher2(1);
System.out.println(teachers);
sqlSession.close();
}
}
小结:
多对一
:association
一对多
:collection
javaType和ofType
:
- javatype用来指定实体类中属性的类型
- ofType用来映射到List或者集合中的实体类类型