Mybatis多表关联查询之多对多

    |     2017年6月15日   |   mytatis   |     0 条评论   |    3793

Mybatis多表关联可分成四种情况:一对一, 一对多, 多对一, 多对多.实现映射的关键是resultMap网上有很多介绍可自行搜索学习,如:MyBatis学习 之 二、SQL语句映射文件(1)resultMap

Mybatis多表关联查询之多对多实现
表结构:

多对多表

类结构

多对多

 

映射文件:

CoursesMapper.xml

<mapper namespace="com.ittx.mybatis.demo1.dao.CoursesDao">
	<resultMap type="com.ittx.mybatis.demo1.model.Courses"
		id="coursesMap">
		<!-- 在默认情况下,mybatis会自动在TypeAliasRegistry初始化的时候挂在很多jdk常用类, 所以javaType="java.lang.Integer"可以写成javaType="Integer" -->
		<id property="id" column="cid" javaType="java.lang.Integer" />
		<result property="name" column="courses_name" javaType="java.lang.String" />
	</resultMap>

	<resultMap type="com.ittx.mybatis.demo1.model.Courses"
		id="couAndStu">
		<id property="id" column="cid" javaType="java.lang.Integer" />
		<result property="name" column="courses_name" javaType="java.lang.String" />

		<!-- 对于一个属性的类型是一个集合,就使用collection 对于一个属性的类型是一个类,就使用association -->
		<collection property="student" column="cid"
			select="findStudentByCourses"></collection>
	</resultMap>

	<!-- 有学生表,课程表这两张表都没有外键,我们就要使用第三张关联表。我们就要根据课程表的fk_cou_id,把学生的id值得到。 对于多对多那么这个学生的id值就不可能是一个值
		。在数据库里就要使用in -->
	<select id="findStudentByCourses" resultMap="com.ittx.mybatis.demo1.dao.StudentDao.studentMap">
		select * from
		t_student where sid in (select fk_stu_id from t_stu_cou where
		fk_cou_id=#{id})
	</select>
	<!--resultMap="coursesMap" 只根据课程id找课程不关联选修课程的学生  -->
	<select id="findCouById" resultMap="coursesMap">
		select * from t_courses where
		cid=#{id}
	</select>
	<!--resultMap="couAndStu" 只根据课程id找课程同时关联查谒选修课程的学生  -->
	<select id="findCouAndStu" resultMap="couAndStu">
		select * from t_courses
		where cid=#{id}
	</select>
</mapper>

StudentMapper.xml

<mapper namespace="com.ittx.mybatis.demo1.dao.StudentDao">

	<resultMap type="com.ittx.mybatis.demo1.model.Student"
		id="studentMap">
		<id property="id" column="sid" javaType="java.lang.Integer" />
		<result property="name" column="student_name" javaType="java.lang.String" />
	</resultMap>

	<resultMap type="com.ittx.mybatis.demo1.model.Student"
		id="studentAndCourses">
		<id property="id" column="sid" javaType="java.lang.Integer" />
		<result property="name" column="student_name" javaType="java.lang.String" />
		<collection property="courses" column="sid"
			select="findCoursesByStudent"></collection>
	</resultMap>

	<select id="findCoursesByStudent" resultMap="com.ittx.mybatis.demo1.dao.CoursesDao.coursesMap">
		select * from t_courses where cid in (select fk_cou_id from t_stu_cou where
		fk_stu_id = #{id})
	</select>
	<!--resultMap="studentMap" 只根据学生id找学生不关联学生选修的课程  -->
	<select id="findStuById" resultMap="studentMap">
		select * from t_student where sid = #{id}
	</select>
	<!--resultMap="studentAndCourses" 只根据学生id找学生同时关联查询学生选修的课程  -->
	<select id="findStuAndCou" resultMap="studentAndCourses">
		select * from t_student where sid = #{id}
	</select>
</mapper>
转载请注明来源:Mybatis多表关联查询之多对多
回复 取消