mybatis 一对多查询
第一步 搭建运行环境
第二步 编写代码
1、创建实体类Teacher和Student,一个老师给多个学生上课,一对多关系
Student
package com.xiahui.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Student { private int id; private String name; private int tid; }
Teacher
package com.xiahui.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor public class Teacher { private int id; private String name; private List<Student> students; }
2、创建Mapper接口
TeacherMapper
package com.xiahui.dao; import com.xiahui.pojo.Teacher; public interface TeacherMapper { Teacher getTeacher(int id); }
3、创建Mapper.xml文件
与多对一类似,一对多也有两种查询方式:查询嵌套,结果嵌套。查询嵌套的实现比较复杂,这里只给出结果嵌套的实现方式(偷懒~)。
TeacherMapper.xml
<?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"> <mapper namespace="com.xiahui.dao.TeacherMapper"> <select id="getTeacher" resultMap="teacherWithStudents"> select * from teacher, student where teacher.id=student.tid and teacher.id=#{id} </select> <resultMap id="teacherWithStudents" type="Teacher"> <result column="id" property="id" /> <result column="name" property="name"/> <collection property="students" javaType="ArrayList" ofType="Student"> <result column="id" property="id"/> <result column="name" property="name"/> </collection> </resultMap> </mapper>
4、在MyBatis的核心配置文件中注册Mapper接口或其xml文件
在 mybatis-config.xml <configuration></configuration>标签内配置
<mappers> <mapper resource="com/xiahui/dao/TeacherMapper.xml"/> </mappers>
第三步 测试
package com.xiahui.dao;
import com.xiahui.pojo.Student;
import com.xiahui.pojo.Teacher;
import com.xiahui.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class TeacherTest {
@Test
public void getTeacher(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
}
小结:
1、association 关联 应用于 多对一
2、collection 集合 应用于 一对多
3、javaType 指定实体类中属性的类型
ofType 指定映射到集合中的pojo类型,泛型的约束类型。
参考 https://www.bilibili.com/video/BV1NE411Q7Nx?p=21