- association(一对一 嵌套结果(一条sql 一次查询))
Tips:
1、resultMap 可以通过extends 实现继承,来简化工作量
2、关联查询设置前缀是一个好习惯
3、通过添加完成整的命名空间,可以引用其他xml文件的resultMap
<resultMap id="userAndPostion" extents="BaseResultMap" type="TUSER">
<association property="postion" javaType="TPosition" columnPrefix="post_">
<id column="id" property="id"/>
<result column="name" property="postName"/>
<result column="note" property="note"/>
</association>
</resultMap>
<select id="selectUserPostion" resultMap="userAndPosition">
select a.id,user_name,sex,b.id post_id, b.name post_name, b.note post_note
from t_user a, t_positiion b
where a.psotion_id = b.id
</select>
association(一对一 嵌套查询(多次查询))
这里我们可以在association 标签上添加fetchType="lazy"(eager),并且把配置文件中setting 下aggressiveLazyLoading 设置成false(按需加载) 来设置成懒加载
<resultMap id="userAndPostion" extents="BaseResultMap" type="TUSER">
<association property="postion" column="position_id" select="com.enjoy.mybatis.mapper.TPositionMapper.selectById"/>
</resultMap>
collection(一对多)
- collection 支持的属性以及属性的作用和association完全相同
- mybatis 会个根据id 标签,进行字段的合并,合理配置好ID 标签可以提高处理效率
discriminator 鉴别器映射
在特定的情况下,根据一个字段去使用不同的pojo进行关联,功能很像java 中的switch;
discriminator 标签常用的两个属性如下:
column:该属性用于设置要进行鉴别比较值的列
javaType:该属性用于指定列的类型,保证使用相同的java类型来比较值discirminator 标签可以有1个或多个case标签,case 标签包含以下三个属性
value:该值为discriminator 指定column用来匹配的值
resultMap:当column的值和value的值匹配时,可以配置使用resultMap指定的映射,resultMap优先级高于resultType
resultType:当column的值和value 的值匹配时,用于配置使用resultType指定的映射
<resultMap id="userAndHealthReport" extends="BaseResultMap" type="User">
<discriminator column="sex" javaType="int">
<case value="1" resultMap="userAndHealthReportMale">
<case value="2" resultMap="userAndHealthReportFemale">
</discriminator>
</resultMap>
<resultMap id="userAndHealthReportMale" extends="userAndHealthReport" type="User">
<collection property="healthReports" column="id" select="com.enjoy.mybatis.HealthReportMalMapper.selectById">
</collection>
</resultMap>
<resultMap id="userAndHealthReportFemale" extends="userAndHealthReport" type="User">
<collection property="healthReports" column="id" select="com.enjoy.mybatis.HealthReportFemalMapper.selectById">
</collection>
</resultMap>