Mybatis学习系列五 关联查询

一对一关联查询

	<!-- 利用resultMap实现一对一 关联查询-->
	<select id="queryStudentByNoWithOO2" resultMap="student_card_map" parameterType = "int" >
		select s.* , c.* from student2 s  inner join studentcard c
		on s.cardid= c.cardid
		where s.stuNo = #{stuNo}
	</select> 
	
	<resultMap type="org.student.entity.Student2" id="student_card_map">
		<!-- 学生信息 -->
		<id  property="stuNo"  column="stuNo"/>
		<result property="stuName"  column="stuName"/>
		<result property="stuAge"  column="stuAge"/>
		
		<!--  一对一时 ,对象成员使用 association映射   javaType指定该属性的类型-->
		<association property="card"  javaType="org.student.entity.StudentCard">
			<id  property="cardid"  column="cardid"/>
			<result  property="cardinfo"  column="cardinfo"/>
		</association>
	</resultMap> 

一对多关联查询

<!-- 一对多 -->
	<select id = "queryClassAndStudents" resultMap = "class_student_map" parameterType="int" >
		<!-- 查询g1班的班级信息, 和g1班的所有学生 -->
		select  c.* , s.* from student2 s inner join studentclass c on c.classid = s.classid
		where c.classid = #{classid}
	</select>
	
	<!-- 类和表的对应关系 -->
	<resultMap type="org.student.entity.StudentClass" id="class_student_map">
		<!-- 因为type的主类是班级,因此先配置班级的信息 -->
		<id property="classid"  column="classid" />
		<result property="className" column="className" />
		
		<!-- 配置成员属性学生, 一对多,属性类型javaType  属性的元素类型 ofType -->
		<collection property="students" ofType="org.student.entity.Student2">
		<id property="stuNo"  column="stuNo" />
		<result  property="stuName"  column="stuName" />
		<result  property="stuAge"  column="stuAge" />
		</collection>
	</resultMap>

小结:

association是用于一对一和多对一,而collection是用于一对多的关系

JavaType和ofType都是用来指定对象类型的

JavaType是用来指定pojo中属性的类型

ofType指定的是映射到list集合属性中pojo的类型(泛型中的约束类型)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值