关联查询的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标签中,这里为了省事省略了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值