MyBatis 之resultMap详解

本文介绍如何使用 MyBatis 的 resultMap 特性进行 1 对 1 和 1 对多的数据映射,通过具体实例展示了如何配置 resultMap 来简化复杂的 SQL 查询结果映射过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景:公司用到MyBatis,学习下resultMap

应用:优化代码,实现复杂业务逻辑

研究方向:1对1查询,1对多查询

1对多查询:

实体类:

public class MisGoods {

  private Integer goods_shop;

  private Integer goods_id;

private List<MisOrderInfo> info;   //如果返回1条数据,MisGoods即可;如果是多条数据,则需List;

//若干set/get 方法

}

*Mapper.xml文件:

 <!-- test begin -->
 <select id="test" resultMap="test">  
  select goods_id,goods_shop 
  from 
  mis_goods ;
 </select>
 
 <resultMap type="MisGoods" id="test">
   <result column="goods_id"  property="goods_id"/> 
 <result column="goods_shop" property="goods_shop" />

 <!-- info:类中属性名称,good_id是MisGoods类中属性 -->

<!--resultMap中可以放多个collection-->
 <collection property="info" column="goods_id" ofType="MisGoods" select="get"/>
 </resultMap>
 <select id="get" parameterType="int" resultType="MisGoods">
  select * from mis_goods ;

select * from mis_goods  where goods_id=#{0};
 </select>
 <!-- test end -->


1对1查询:

public class MisGoods {

 private Integer goods_id;
    private Integer goods_shop;

 private MisOrderInfo order;

}

 <!-- test begin -->
 <select id="test" resultMap="test">
  select 
  b.goods_id,b.goods_shop,a.info_id,a.info_goods 
  from mis_order_info a, mis_goods b
where 
b.goods_id = a.info_id
and b.goods_id=2;
 </select>
 <!--order是类属性名 info_id,info_goods都是类MisOrderInfo的属性-->
 <resultMap type="MisGoods" id="test">
    <id property="goods_id" column="goods_id" />  
    <result property="goods_shop" column="goods_shop" />  
    <association property="order" javaType="MisOrderInfo">  
        <id property="info_id" column="info_id" />  
        <result property="info_goods" column="info_goods" />  
    </association>  
</resultMap>  
 
 <!-- test end -->


鉴别器:

 <discriminator javaType="string" column="sex">
13             <case value="男" resultMap="maleStudentMap"/>
14             <case value="女" resultMap="femaleStudentMap"/>
15         </discriminator>
<discriminator column="during" javaType="_int">
    // 形式1:通过resultType设置动态映射信息
    <case value="4" resultType="EStudent">
      <result column="juniorHighSchool" property="seniorHighSchool"/>
    </case>

   // 形式2: 通过resultMap设置动态映射信息
   <case value="5" resultMap="dynamicRM"/>
   <case value="6" resultMap="dynamicRM"/>
  </discriminator>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值