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>
时间: 2024-12-15 22:55:11