Mybatis查询返回结果类型专题


一、返回一条信息

Student selectById(Long id);
不再赘述

二、返回List集合

List< Student> selectAll();
不再赘述

三、返回Map集合

用map集合去接收返回来的结果
字段名叫做key,字段值叫做value

接口:

    /**
     * 根据id获取student信息,将学生信息放在map集合中
     * @param id
     * @return
     */
    Map<String,Object> selectByIdReturnMap(Long id);

mapper.xml

    <select id="selectByIdReturnMap" resultType="map">
        select * from t_student where id=#{id}
    </select>

测试:

    @Test
    public void testSelectByIdReturnMap() throws IOException, ParseException {
        SqlSession session = SqlSessionUtil.openSession();
        StudentMapper mapper = session.getMapper(StudentMapper.class);
        Map<String, Object> studentMap = mapper.selectByIdReturnMap(1L);
        System.out.println(studentMap);
        session.close();
    }

运行结果:

在这里插入图片描述

四、返回多个Map集合

List< Map > 等同于List< Student>
返回多个map,可以list集合套map

接口:

List<Map<String,Object>> selectAll();

mapper.xml:
注意:resultType不是student不是list 还是map!!!

    <select id="selectAll" resultType="map">
        select * from t_student
    </select>

测试:

    @Test
    public void testSelectAll() throws IOException, ParseException {
        SqlSession session = SqlSessionUtil.openSession();
        StudentMapper mapper = session.getMapper(StudentMapper.class);
        List<Map<String, Object>> maps = mapper.selectAll();
        maps.forEach(studentmap->{
            System.out.println(studentmap);
        });
        session.close();
    }

运行结果:
在这里插入图片描述

五、返回List集合

在第四种方式的基础上,如果想要获取id为3的学生就需要对List集合中的每一个元素进行遍历,再遍历map集合的id属性。查询起来较为麻烦。
搞一个更大的Map<String,Map >集合由key和value组成。
student的id值作为这个大map集合的key,第四种方式下的小map集合作为大map集合的value值

拿student的id做key,以后取出对应的map集合时较为方便

通过 @MapKey(“id”) 注解将查询结果的id值作为大map集合的key

接口:

    /**
     * 查询所有的Student,返回一个大Map集合
     * Map集合的key是每条记录的主键值
     * Map集合的value是每条记录
     * 通过MapKey这个注解来指定map集合的key
     * @return
     */
    @MapKey("id") //将查询结果的id值作为大map集合的key
    Map<Long,Map<String,Object>> selectAllReturnBigMap();

mapper.xml:

注意:这里的resultType依然是Map

    <select id="selectAllReturnBigMap" resultType="map">
        select * from t_student
    </select>

测试:

    @Test
    public void testSelectAllReturnBigMap() throws IOException, ParseException {
        SqlSession session = SqlSessionUtil.openSession();
        StudentMapper mapper = session.getMapper(StudentMapper.class);
        Map<Long, Map<String, Object>> studentMapMap = mapper.selectAllReturnBigMap();
        System.out.println(studentMapMap);
        session.close();
    }

运行结果:
大Map集合
{
1={sex=男, name=阿白, birth=1999-10-04, id=1, age=23, height=1.58},
2={sex=女, name=阿川, birth=1999-09-30, id=2, age=23, height=1.75},
3={sex=女, name=小小川, birth=1998-09-29, id=3, age=24, height=1.78}
}
在这里插入图片描述


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值