当前位置:   article > 正文

Mybatis实现多表查询(一对多 、多对一)_mybatis 一对多查询

mybatis 一对多查询

多对一和一对多的关系说明:以多个学生对一位老师为例

1. 对学生这方面说 : 使用关键"关联" association 就是多个学生关联一个老师 -----------多对一
2. 对老师来说: 使用关键字“集合” collection, 就是 一个老师有很多学生 (集合)---------一对多

一、创建数据库

  1. create table teacher(
  2. id int not null primary key ,
  3. name varchar(50) not null
  4. )ENGINE =INNODB DEFAULT CHARSET=utf8;
  5. insert into teacher(id,name) values (1001,"刘老师"),(1002,"叶老师"),(1003,"张老师");
  6. create table student(
  7. id int not null primary key,
  8. name varchar(50) not null,
  9. age int not null ,
  10. tid int default null,
  11. constraint `fk` foreign key (`tid`) references `teacher`(`id`)
  12. )ENGINE =INNODB DEFAULT CHARSET=utf8 collate utf8_general_ci
  13. insert into student(id,name,age,tid) values (1201,"王冬雪",20,1001),
  14. (1202,"好平平",19,1001),
  15. (1203,"刘美玲",18,1001),
  16. (1204,"王海华",32,1001),
  17. (1205,"张李",34,1001),
  18. (1206,"江风",45,1001),
  19. (1207,"任丽",67,1001);
  20. insert into student(id,name,age,tid) values (1201,"王冬雪",20,1001),
  21. (1202,"好平平",19,1001),
  22. (1203,"刘美玲",18,1001),
  23. (1204,"王海华",32,1001),
  24. (1205,"张李",34,1001),
  25. (1206,"江风",45,1001),
  26. (1207,"任丽",67,1001);
  27. insert into student(id,name,age,tid) values (1301,"李小龙",20,1002),
  28. (1302,"王美玲",19,1002),
  29. (1303,"和小",18,1002),
  30. (1304,"王丹丹",32,1002),
  31. (1305,"厚天天",34,1002),
  32. (1306,"李大明",45,1002),
  33. (1307,"李铁",43,1002);
  34. insert into student(id,name,age,tid) values (1401,"王小妹",20,1003),
  35. (1402,"李大牛",19,1003),
  36. (1403,"杨杨",18,1003),
  37. (1404,"王二小",32,1003),
  38. (1405,"李芬丽",34,1003),
  39. (1406,"牛小同",45,1003),
  40. (1407,"和小明",23,1003);

二、多对一和一对多

第一步:导包

  1. <dependency>
  2. <groupId>org.projectlombok</groupId>
  3. <artifactId>lombok</artifactId>
  4. <version>1.18.16</version>
  5. </dependency>

第二步:创建实体类Teacher、Student

Teacher

  1. package ljg.com.pojo;
  2. import lombok.*;
  3. import java.util.List;
  4. @Data
  5. @AllArgsConstructor
  6. @NoArgsConstructor
  7. @Setter
  8. @Getter
  9. public class Teacher {
  10. private int id;
  11. private String name;
  12. // 一个老师拥有多个学生
  13. private List<Student> students;
  14. }

Student 

  1. package ljg.com.pojo;
  2. import lombok.*;
  3. @Data//提高代码的简洁,可以省去实体类中大量的get()、set()、toString()等方法
  4. @AllArgsConstructor//注解版全参
  5. @NoArgsConstructor//注解版无参
  6. @Setter
  7. @Getter
  8. public class Student {
  9. private int id;
  10. private String name;
  11. private int age;
  12. //学生需要关联一个老师 多对一
  13. private Teacher teacher;
  14. //一对多,一个老师拥有多个学生
  15. //只有一个老师
  16. private int tid;
  17. }

第三步:建立mapper接口

  1. package ljg.com.mapper;
  2. import ljg.com.pojo.Student;
  3. import org.apache.ibatis.annotations.Param;
  4. import org.apache.ibatis.annotations.Select;
  5. import java.util.List;
  6. public interface StudentMapper {
  7. //@Select mybatis注解 用于映射sql语句
  8. @Select("select * from student where id = #{sid}")
  9. // @Param的作用就是给参数命名,
  10. // 比如在mapper里面某方法A(int id),
  11. // 当添加注解后A(@Param("sid") int id),
  12. // 也就是说外部想要取出传入的id值,
  13. // 只需要取它的参数名sid就可以了。
  14. // 将参数值传如SQL语句中,通过#{sid}进行取值给SQL的参数赋值。
  15. Student getStudent(@Param("sid") int id);
  16. List<Student> getStudents();
  17. List<Student> getStudents2();
  18. }
  1. package ljg.com.mapper;
  2. import ljg.com.pojo.Teacher;
  3. import org.apache.ibatis.annotations.Param;
  4. import org.apache.ibatis.annotations.Select;
  5. import java.util.List;
  6. public interface TeacherMapper {
  7. @Select("select * from teacher where id = #{tid}")
  8. Teacher getTeacher(@Param("tid") int id);
  9. //测试
  10. List<Teacher> getTeacher3();
  11. // 获取一个老师 获取指定老师下的所有及老师的信息
  12. Teacher getTeacher1(@Param("tid") int id);
  13. // 子查询
  14. Teacher getTeacher2(@Param("tid") int id);
  15. }

第四步:建立Mapper.xml文件

StudentMapper.xml(多对一)

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="ljg.com.mapper.StudentMapper">
  6. <!--按照结果嵌套处理 联表查询-->
  7. <select id="getStudents2" resultMap="StudentTeacher2" >
  8. select s.id as sid,s.name as sname,age as sage,t.name as tname
  9. from student s,teacher t
  10. where s.tid=t.id
  11. </select>
  12. <resultMap id="StudentTeacher2" type="Student">
  13. <!--学生的属性id对应 sid 一一对应-->
  14. <result property="id" column="sid"/>
  15. <result property="name" column="sname"/>
  16. <result property="age" column="sage"/>
  17. <association property="teacher" javaType="Teacher">
  18. <!--老师是个复杂类型 结果处理完了 再去映射老师里面对应的字段-->
  19. <result property="name" column="tname"/>
  20. </association>
  21. </resultMap>
  22. <!--/
  23. 1.查询所有的学生信息
  24. 2.根据查询出来的学生的tid,寻找对应的老师
  25. -->
  26. <!-- 按照查询嵌套处理-->
  27. <select id="getStudents" resultMap="StudentTeacher">
  28. select * from student
  29. </select>
  30. <!--结果集映射将两个关联起来,解决属性名和字段名不一致的问题-->
  31. <resultMap id="StudentTeacher" type="Student">
  32. <!--主键,一一对应-->
  33. <result column="id" property="id"/>
  34. <result column="name" property="name"/>
  35. <result column="age" property="age"/>
  36. <!-- //property参数类型名
  37. //column字段名
  38. //javaType实体类中属性的类型
  39. //select 嵌套语句-->
  40. <!--复杂的属性需要单独处理,对象(老师):association javaType:用来指定实体类中属性的类型,select在进行嵌套查询-->
  41. <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
  42. </resultMap>
  43. <!--tid 下面id没必要一一对应,mybatis会自行去推断-->
  44. <select id="getTeacher" resultType="Teacher">
  45. select * from Teacher where id=#{tid}
  46. </select>
  47. </mapper>
说明:上述代码详细说明了多对一的两种方法,分别是查询嵌套处理和结果嵌套处理。

TeacherMapper.xml (一对多)

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="ljg.com.mapper.TeacherMapper">
  6. <select id="getTeacher3" resultType="Teacher">
  7. select * from xsgl2.teacher;
  8. </select>
  9. <!--按照结果嵌套-->
  10. <select id="getTeacher1" resultMap="TeacherStudent">
  11. select s.id sid, s.name sname,s.age sage,t.id tid,t.name tname
  12. from teacher t ,student s
  13. where t.id=s.tid and t.id=#{tid}
  14. </select>
  15. <resultMap id="TeacherStudent" type="Teacher">
  16. <result property="id" column="tid"/>
  17. <result property="name" column="tname"/>
  18. <!--javaType时属性的类型,集合中的泛型信息,我们使用ofType获取-->
  19. <!--不用写javaType因为直接取出来的每一个值,然后去一一对应-->
  20. <collection property="students" ofType="Student">
  21. <result property="id" column="sid"/>
  22. <result property="name" column="sname"/>
  23. <result property="age" column="sage"/>
  24. <result property="tid" column="tid"/>
  25. </collection>
  26. </resultMap>
  27. <!--查询嵌套处理-->
  28. <select id="getTeacher2" resultMap="TeacherStuden2">
  29. select * from xsgl2.teacher where id =#{tid}
  30. </select>
  31. <resultMap id="TeacherStuden2" type="Teacher">
  32. <!--
  33. private List<Student> students;
  34. list 是Java类型 用 javaType="ArrayList"
  35. <Student> 是范型数据 用 ofType="Student
  36. select="getByTidOfStudents" 根据老师的id查询对应的学生
  37. tid=#{tid} 这个结果就是老师的ID
  38. -->
  39. <!--本来就是个集合 集合对象和泛型信息写出来-->
  40. <collection property="students" javaType="ArrayList" ofType="Student"
  41. select="getByTidOfStudents" column="id"/>
  42. </resultMap>
  43. <!--两个语句查询再通过子查询去查一次getByTidOfStudents-->
  44. <select id="getByTidOfStudents" resultType="Student">
  45. select * from xsgl2.student where tid=#{tid}
  46. </select>
  47. </mapper>
说明:上述代码详细说明了多对一的两种方法,分别是查询嵌套处理和结果嵌套处理。

第五步:测试类

  1. package ljg.com.test;
  2. import ljg.com.mapper.StudentMapper;
  3. import ljg.com.mapper.TeacherMapper;
  4. import ljg.com.pojo.Student;
  5. import ljg.com.pojo.Teacher;
  6. import ljg.com.utils.MybatisUtils;
  7. import org.apache.ibatis.session.SqlSession;
  8. import org.junit.jupiter.api.Test;
  9. import java.util.List;
  10. public class YouTest {
  11. //搭配环境
  12. @Test
  13. public void getteacher(){
  14. SqlSession salSession = MybatisUtils.getSqlSession();
  15. StudentMapper mapper = salSession.getMapper(StudentMapper.class);
  16. Student student = mapper.getStudent(1201);
  17. System.out.println(student);
  18. TeacherMapper mapper1 = salSession.getMapper(TeacherMapper.class);
  19. Teacher teacher = mapper1.getTeacher(1001);
  20. System.out.println(teacher);
  21. }
  22. //多对一
  23. // 第一种方法 查询嵌套处理
  24. @Test
  25. public void getstudent(){
  26. SqlSession salSession = MybatisUtils.getSqlSession();
  27. StudentMapper mapper = salSession.getMapper(StudentMapper.class);
  28. List<Student> students = mapper.getStudents();
  29. for (Student student : students) {
  30. System.out.println(student);
  31. }
  32. }
  33. //第二种方法 结果嵌套查询
  34. @Test
  35. public void getstudent1(){
  36. SqlSession salSession = MybatisUtils.getSqlSession();
  37. StudentMapper mapper = salSession.getMapper(StudentMapper.class);
  38. List<Student> students = mapper.getStudents2();
  39. for (Student student : students) {
  40. System.out.println(student);
  41. }
  42. }
  43. @Test
  44. public void getTeacher1(){
  45. SqlSession sqlSession = MybatisUtils.getSqlSession();
  46. TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
  47. Teacher teacher = mapper.getTeacher1(1002);
  48. System.out.println(teacher);
  49. sqlSession.close();
  50. }
  51. @Test
  52. public void getTeacher2(){
  53. SqlSession sqlSession = MybatisUtils.getSqlSession();
  54. TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
  55. Teacher teacher = mapper.getTeacher2(1002);
  56. System.out.println(teacher);
  57. sqlSession.close();
  58. }
  59. @Test
  60. public void getTeacher3(){
  61. SqlSession sqlSession = MybatisUtils.getSqlSession();
  62. for (Teacher teacher :sqlSession.getMapper(TeacherMapper.class).getTeacher3()){
  63. System.out.println(teacher);
  64. }
  65. sqlSession.close();
  66. }
  67. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/830575
推荐阅读
相关标签
  

闽ICP备14008679号