多表集合嵌套查询

Posted Zenz

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多表集合嵌套查询相关的知识,希望对你有一定的参考价值。

1.创建数据库表

CREATE TABLE course(
  c_id INT(5) PRIMARY KEY,
  c_name VARCHAR(20)
);

CREATE TABLE students(
  s_id INT(5) PRIMARY KEY,
  s_name VARCHAR(20),
  s_sal DOUBLE(8,2)
);

CREATE TABLE students_course(
  s_id INT(5),
  c_id INT(5)
);

 2.创建javabean

public class Students {
    private Integer sId;
    private String sName;
    private Double sSal;
    //一个学生选多门课程
    private List<Course> courseList;
}

public class Course {
    private Integer cId;
    private String cName;
}

 3.映射文件

StudentsMapper。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="org.zenzzat.toa.core.test.dao.StudentsMapper" >
  <resultMap id="CourseResultMap" type="org.zenzzat.toa.core.test.entity.Course" >
    <id column="c_id" property="cId" jdbcType="INTEGER" />
    <result column="c_name" property="cName" jdbcType="VARCHAR" />
  </resultMap>
  <resultMap id="StudentsResultMap" type="org.zenzzat.toa.core.test.entity.Students" >
    <id column="s_id" property="sId" jdbcType="INTEGER" />
    <result column="s_name" property="sName" jdbcType="VARCHAR" />
    <result column="s_sal" property="sSal" jdbcType="DOUBLE" />
    <collection property="courseList" column="s_id" javaType="ArrayList" ofType="org.zenzzat.toa.core.test.entity.Course"
                select="selesctCourseInStudents"/>
  </resultMap>

  <select id="selectStudents" parameterType="int" resultMap="StudentsResultMap">
    SELECT * FROM students
    WHERE s_id = #{sId};
  </select>


  <select id="selesctCourseInStudents" parameterType="int" resultMap="CourseResultMap">
    SELECT * FROM course
    WHERE c_id IN (SELECT sc.c_id FROM students_course sc WHERE sc.s_id = #{sId});
  </select>

</mapper>

 

以上是关于多表集合嵌套查询的主要内容,如果未能解决你的问题,请参考以下文章

Room多表查询不能嵌套

MySQL 基础 -- 多表关系(一对一1对多(多对一)多对多)多表查询(内连接外连接自连接子查询(嵌套查询)联合查询 union)笛卡儿积

MySQL的多表联查和嵌套查询

mybatis-基于xml的多表查询

Mybatis 的嵌套查询与嵌套结果的区别

Mybatis 的嵌套查询与嵌套结果的区别