实现多表查询的方法
- 业务装配:对两个或多个表编写单表查询语句,在业务(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>
未完待续