0
点赞
收藏
分享

微信扫一扫

关联查询的resultMap写法示例


对于自定义对象一般使用association,对于集合一般使用collection。


对于一般的自定义对象

1、使用子查询:

<resultMap id="BaseResultMapWithItemInfo" type="com.xxx.biz.cases.model.ShCase" extends="BaseResultMap">
<association property="applyBillDetailList" column="SERVICE_ID" select="com.xxx.biz.dao.ApplybillDetailMapper.getBriefInfoByServiceId" />
<association property="commentSpList" column="SERVICE_ID" select="com.xxx.biz.dao.ServicePartcommentMapper.getCommentSpBriefInfoByServiceId" />
<association property="finalUseSpList" column="SERVICE_ID" select="com.xxx.biz.dao.ServicePartcommentMapper.getFinalUseSpBriefInfoByServiceId" />
</resultMap>



2、不使用子查询:

<resultMap type="org.apache.ibatis.submitted.associationtest.Car" id="carResult">  
<id column="carid" property="id"/>
<result column="cartype" property="type"/>
<association property="engine" resultMap="engineResult"/>
<association property="brakes" resultMap="brakesResult"/>
</resultMap>
<resultMap type="org.apache.ibatis.submitted.associationtest.Engine" id="engineResult">
<result column="enginetype" property="type"/>
<result column="enginecylinders" property="cylinders"/>
</resultMap>
<resultMap type="org.apache.ibatis.submitted.associationtest.Brakes" id="brakesResult">
<result column="brakesType" property="type"/>
</resultMap>



或者类似如下写法:

<resultMap type="org.apache.ibatis.submitted.associationtest.Car" id="carResult">  
<id column="carid" property="id"/>
<result column="cartype" property="type"/>
<association property="engine" javaType="org.apache.ibatis.submitted.associationtest.Engine">
<result column="enginetype" property="type"/>
<result column="enginecylinders" property="cylinders"/>
</association>
</resultMap>



这样会自动在sql查询结果里找到相应的字段来组成相应的对象。



对于list

1、使用子查询:

<resultMap type="com.xxx.base.sys.domain.User" id="userWithRolesMap" extends="BaseResultMap">
<collection property="roles" column="id" javaType="list" select="com.xxx.base.sys.dao.RoleMapper.selectUserRoleByUserId"> </collection>
</resultMap>



2、当然,也可以不使用子查询

<collection property="tags" javaType="list" ofType="Tag" >  
<id property="id" column="tag_id"/>
</collection>


这会让mybatis自动进行一个类似group by的操作,将所有其他字段重复的数据合并,然后将tag_id作为Tag的id属性拼成一个List<Tag>,这样做效率高一些,但是使用场景也是有限的。


3、如果list中的对象是String

<collection property="tags" javaType="list" ofType="String" >  
<result column="tag_id"/>
</collection>



注意,以上2和3中collection标签和1一样,都应该包裹在resultMap标签中,这里为了省事省略了


举报

相关推荐

0 条评论