MyBatis日常笔记记录06--Map和resultMap

一、Map

sql查询结果作为Map的key和value,推荐使用Map<Object,Object>

注意:Map作为接口返回值,sql语句的查询结果最多只能有一条记录大于一条记录是错误的。

在dao接口中定义下面这个方法

Map<Object,Object> selectMapById(Integer id);


在mapper映射文件中这样定义,注意全限定的名称
    <select id="selectMapById" resultType="java.util.HashMap">
        select id , name from student where id=#{stuid}
    </select>

测试方法

    @Test
    public void selectMapById(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);

        Map<Object, Object> map = dao.selectMapById(1001);
        System.out.println("map==" + map);
    }

 

二、resultMap

resultMap:结果映射,指定列名和Java对象的属性对应关系

1.你自定义列值赋值给哪个属性

2.当你的列名和属性名不一样时,一定使用resultMap

注意:resultMap和resultType不要一起使用,二选一

 

在dao接口中定义下面这个方法

List<Student> selectAllStudents();

在mapper映射文件定义方式

   <!--使用resultMap
        1.先定义resultMap
        2.在select标签,使用resultMap来引用定义的
    -->
    <!--定义resultMap
        id:自定义名称,表示你定义的这个resultMap
        type:java类型的全限定名称
    -->
    <resultMap id="studentMap" type="com.example.domain.Student">
        <!--列名和java属性的关系
            注解列,使用id标签
            column:列名
            property:java类型的属性名
        -->
        <id column="id" property="id"/>
        <!--非主键列,使用result-->
        <result column="name" property="name"/>
        <result column="email" property="email"/>
        <result column="age" property="age"/>
    </resultMap>

    <select id="selectAllStudents" resultMap="studentMap">
        select id,name,email,age from student
    </select>

测试方法

    @Test
    public void selectAllStudents() {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);

        List<Student> students = dao.selectAllStudents();

        for (Student stu : students) {
            System.out.println("学生:" + stu);
        }
        sqlSession.close();
    }

 

posted @ 2021-07-06 00:19  Brack_Pearl  阅读(84)  评论(0编辑  收藏  举报