课时16:使用HashMap存储查询结果集

.1)使用返回值为Map 查询单个数据的时候

  1.配置如下

<!--    返回值为map-->
    <select id="queryStudentById" resultType="java.util.Map">
        select stuNo "no",stuName "name",stuAge "age",stuSex "sex" from student where stuno=#{id};
    </select>

    1.1 其中stuNo是数据库的字段名,"no"是stuNo的别名,用于在map中get值时使用(作为map的key)。map.get("name......");

  2.如果不起别名,则map的key就是字段名

<!--    返回值为map-->
    <select id="queryStudentById" resultType="java.util.Map">
        select stuNo ,stuName ,stuAge ,stuSex  from student where stuno=#{id};
    </select>

.2)使用返回值为Map 查询多个数据的时候

  1.在SQL映射文件中编写

<!--    多个学生返回的map对象-->
    <select id="queryStudent" resultType="java.util.Map">
        select * from student
    </select>

    1.1 mybatis会自动的吧这个返回值封装成一个对象存储

  2. 值已经封装了,通过@MapKey("")来指定数据库的哪一个字段来作为这个map的key

@MapKey("stuno")
    Map<Integer,Student> queryStudent();

    2.1 注意:@MapKey("stuno")里面填写的值必须与数据库字段一模一样 不一样除非起别名 不然会key会是null

  3.结果:

{1={stuSex=1, graName=S1, stuName=ol, stuAge=12, stuno=1}, 2={stuSex=1, graName=S1, stuName=plp, stuAge=12, stuno=2}, 3={stuSex=1, graName=aji, stuName=何哥哥, stuAge=24, stuno=3}, 4={stuSex=1, graName=aji, stuName=何哥哥001, stuAge=24, stuno=4}, 5={stuSex=1, graName=S1, stuName=ji, stuAge=23, stuno=5}, 6={stuSex=1, graName=S1, stuName=lo, stuAge=23, stuno=6}, 7={stuSex=1, graName=S3, stuName=kkk, stuAge=55, stuno=7}}

posted @ 2020-03-10 20:18  何邦柱  阅读(436)  评论(1编辑  收藏  举报