mybatis :关联查询

在mybatis中对于关联查询分为两种情况,一对一和一对多。
两张表连接起来时,相对应的,实体类中应该增加一个属性来维护两者之间的关联关系。

一对一

现在,要求查询学生和学生卡信息,一个学生对应一张学生卡,所以学生类中应该有一个学生卡属性,这个属性就维护了学生和学生卡之间一对一的关系。

mapper.xml

<select id="queryStudent1To1WithSid" parameterType="String" resultMap="student_card_map">
		select s.*,scd.* from student s inner join studentcard scd on s.sid = scd.sid
		<where>
			s.sid = #{sid}
		</where>
	</select>
	<resultMap type="entities.Student" id="student_card_map">
		<id property="sid" column="sid"/>
		<result property="sname" column="sname"/>
		<!-- 一对一时,对象属性使用association映射;JavaType指定该属性的类型 -->
		<association property="card" javaType="entities.StudentCard">
			<id property="sid" column="sid"/>
			<result property="cardinfo" column="cardinfo"/>
		</association>
	</resultMap>

一对一关联查询时要用到association 标签有如下常用属性

  • property:对象属性的名称
  • javaType:对象属性的类型
  • column:所对应的外键字段名称
  • select:使用另一个查询封装的结果

一对多

一个班级中有多个学生,于是需要在班级中设置一个List<Student> students用于维系班级和学生之间的一对多关系。

mapper.xml

<!-- 一对多 -->
	<select id="queryClassAndStudent" parameterType="int" resultMap="class_student_map">
		select s.*,sc.* from student s inner join studentclass sc on s.classid=sc.classid 
		<where>
			sc.classid=#{classid};
		</where>
		
	</select>
	<resultMap type="entities.StudentClass" id="class_student_map">
		<id property="classid" column="classid"/>
		<result property="classname" column="classname"/>
		<collection property="students" ofType="entities.Student">
			<id property="sid" column="sid"/>
			<result property="sname" column="sname"/>
		</collection>
	</resultMap>

一对多关联查询时要用到collection 标签,注意:collection 中ofType属性指定集合中元素的类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值