Mybatis笔记(七)--多表查询

实现多表查询的方法
  • 业务装配:对两个或多个表编写单表查询语句,在业务(Service)把查询的两个结果进行关联。
  • 使用Auto Mapping特征,在实现两表联合查询时通过别名完成映射。
  • 使用Mybatis的resultMap属性进行实现。
resultMap属性
  • resultMap属性写在mapper.xml中,由程序员控制SQL查询结果与实体类的映射关系。
    • 默认Mybatis使用Auto Mapping特性。
  • 使用resultMap属性时,select标签不写resultType属性,而是使用resultMap属性。
  • 其中实体类为
    在这里插入图片描述
  • 数据库中的变量为
    在这里插入图片描述
  • 在mapper中的设置语句:
	<mapper namespace="a.b">
		<resultMap type="teacher" id="mymap">
			<!-- 主键使用id标签配置映射关系 -->
			<id column="id" property="id1"/>
			<!-- 其他类使用result标签配置映射关系 -->
			<result column="name" property="name2"/>
		</resultMap>
		
		<select id="selAll" resultMap="mymap">
			select * from teacher
		</select>
	</mapper>
resultMap的N+1模式
	<mapper namespace="c.d">
		
	 	<!-- n+1模式 -->
	 	<resultMap type="student" id="stumap">
	 		<id column="id" property="id" />
	 		<result column="name" property="name" />
	 		<result column="age" property="age" />
	 		<result column="tid" property="tid"/>
	 		<!-- 关联一个对象 -->
	 		<!-- column中为传递的属性 -->
	 		<association property="teacher" select="c.d.selById" column="tid">		</association>
	 	</resultMap>
	 		
	 	<select id="selAll" resultMap="stumap">
	 		select * from student;
	 	</select>
	 	
		<select id="selById" resultType="teacher" parameterType="int">
			select * from teacher where id = #{param1}
		</select>
	 </mapper> 

未完待续

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值