比如现在有三张表t_grade、t_class、t_student
通过t_student的class_sn可以查到对应的class,通过class_sn可以查到对应的grade,我们在为这张表配置映射文件时大致是这种结构:
<resultMap id="studentResultMap" type="Student">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sn" column="sn"/>
<association property="class"
javaType="Student"
column="class_sn"
select="cn.itsource.crm.mapper.ClassMapper.selectBySn"/>
</resultMap>
<select id="selectBySn" resultMap="classResultMap">
SELECT id,name,sn,grade_sn FROM t_class WHERE sn=#{sn}
</select>
<resultMap id="classResultMap" type="Class">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sn" column="sn"/>
<association property="grade"
javaType="Grade"
column="grade_sn"
select="cn.itsource.crm.mapper.GradeMapper.selectBySn"/>
</resultMap>
也就是说应该通过子查询的方式来,在先前这个地方
<association property="class"
javaType="Student"
column="class_sn"
select="cn.itsource.crm.mapper.ClassMapper.selectBySn"/>
不能使用关联,适用关联的话就是association里面还有一个association,也就是关联和子查询一起使用了,这样业务逻辑多了的话会造成代码冗余,应该要么都是子查询,要么都是关联。
还有一个例子就是通过父查到所有子,每个子中都应该包含父的信息:
<resultMap id="permissionResultMap" type="Permission">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sn" column="sn"/>
<result property="resource" column="resource"/>
<association property="parent"
javaType="Permission"
column="parent_sn"
select="cn.itsource.crm.mapper.PermissionMapper.selectBySonSn"/>
<collection property="children"
javaType="ArrayList"
ofType="Permission"
column="sn"
select="cn.itsource.crm.mapper.PermissionMapper.selectByParentSn">
</collection>
</resultMap>
<select id="selectBySonSn" resultType="Permission">
SELECT * FROM t_permission WHERE sn=#{sn}
</select>
<select id="selectByParentSn" resultMap="permissionResultMap">
SELECT * FROM t_permission WHERE parent_sn=#{sn}
</select>
myllxy
发布了148 篇原创文章 · 获赞 34 · 访问量 4万+
私信
关注