码迷,mamicode.com
首页 > 其他好文 > 详细

多表集合嵌套查询

时间:2016-06-08 20:19:17      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

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>

 

多表集合嵌套查询

标签:

原文地址:http://www.cnblogs.com/zen4j/p/5571166.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!