06 sql映射之返回值类型(resultType)


resultType属性就是指定返回值类型,这一章节主要介绍resultType属性

1 返回集合

如果返回值是一个集合,resultType并非指定为集合类型,而是指定为集合内元素的类型

比如:

List<TbUser> selectAll();
<!--
 如果返回值是一个集合,resultType并非指定为集合类型,`而是指定为集合内元素的类型`
 -->
<select id="selectAll" resultType="TbUser">
   select
       *
   from
       tb_user
</select>

测试:

@Test
public void test01() {
    List<TbUser> list = tbUserMapper.selectAll();
    System.out.println(list);
}

2 返回Map

  1. key就是列名,value就是对应的数据,resultType指定为map

比如:

Map<String, Object> selectById(@Param("id") Long id);
<select id="selectById" resultType="map">
    select
        *
    from
        tb_user
    where
        id = #{id}
</select>

测试:

@Test
public void test02() {
    Map<String, Object> map = tbUserMapper.selectById(1L);
    System.out.println(map);
}

输出结果:

{password=123456, update_time=2019-04-04 22:58:26.0, create_time=2019-04-04 22:58:26.0, phone=13100001111, id=1, username=kobe}
  1. 返回的map,key是主键,value是这个主键对应的数据呢
    • resultType指定为map
    • 在mapper接口中使用MapKey注解指定,返回map的key
@MapKey("id")
Map<Long, TbUser> selectMap();
<select id="selectMap" resultType="map">
   select
       *
   from
       tb_user
</select>

测试:

@Test
public void test03() {
    Map<Long, TbUser> map = tbUserMapper.selectMap();
    for (Long id : map.keySet()) {
        System.out.println(id + "--->" + map.get(id));
    }
}

输出:

1--->{password=123456, update_time=2019-04-04 22:58:26.0, create_time=2019-04-04 22:58:26.0, phone=13100001111, id=1, username=kobe}
5--->{password=123456, update_time=2021-01-31 11:44:22.0, create_time=2021-01-31 11:44:22.0, phone=13011112222, id=5, username=t-mac}
6--->{password=123456, update_time=2021-01-31 11:44:56.0, create_time=2021-01-31 11:44:56.0, phone=13011112222, id=6, username=t-mac}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值