天天看点

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

文章目录

    • 1 返回集合
    • 2 返回Map

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

1 返回集合

如果返回值是一个集合,resultType并非指定为集合类型,

而是指定为集合内元素的类型

比如:

<!--
 如果返回值是一个集合,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

比如:

<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);
}
           

输出结果:

  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}
           

继续阅读