栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

MyBatis中resultType和resultMap的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MyBatis中resultType和resultMap的使用

封装输出结果:MyBatis执行sql语句,得到ResultSet,转为java对象

这里我们两个,分别为resultType和resultMap

文章目录
    • 1.resultType
      • 1.1 java类型的全限定名称
      • 1.2 自定义别名
        • 1.2.1 typeAlias自定义别名
        • 1.2.2 package自定义别名
      • 1.3 resultType表示简单类型
      • 1.4 resultType
    • 2.resultMap
    • 3.列名和Java对象属性名称不一致解决方式
      • 3.1 使用resultMap:自定义列名和属性名称对应关系
      • 3.2 使用resultType

1.resultType

resultType属性:在执行select时使用,作为标签的属性出现的。

resultType:执行sql得到ResultSet转换的类型,使用类型的完全限定名或别名。注意如果返回的是集合,那应该设置为集合包含的类型,而不是集合本身。

它的值有两种:

  1. java类型的全限定名称
  2. 使用别名
1.1 java类型的全限定名称

dao接口中定义方法

Student selectStudentById(Integer id);

mapper文件中


	select id, name, email, age from student where id = #{studentId}

3.测试类中测试

    @Test
    public void testselectStudentById() {
        SqlSession session = MyBatisUtil.getSqlSession();
        StudentDao dao = session.getMapper(StudentDao.class);
        Student student = dao.selectStudentById(1002);
        System.out.println(student);
        session.close();
    }

控制台输出:


使用typeAlias有优点也有缺点

优点:别名可以自定义

缺点:每个类型必须单独定义

1.2.2 package自定义别名

主配置文件中:


mapper文件中:


	select count(*) from student

在测试类中测试

    @Test
    public void testCountStudent() {
        SqlSession session = MyBatisUtil.getSqlSession();
        StudentDao dao = session.getMapper(StudentDao.class);
        long nums = dao.countStudent();
        System.out.println("nums = " + nums);

        session.close();
    }

控制台输出:

1.4 resultType

dao接口中定义方法:

Map selectMap(Integer id);

mapper文件中写sql语句:


        select id, name, email, age from student where id = #{studentid}
    

这样我们就可以使用resultMap来定义数据库列和属性的关系

我们在测试类中进行测试:

    @Test
    public void testSelectById2() {
        SqlSession session = MyBatisUtil.getSqlSession();
        StudentDao dao = session.getMapper(StudentDao.class);
        CustomObject co = dao.selectById2(1001);
        System.out.println(co);
        session.close();
    }

控制台输出:


这样resultMap就成功解决了列名和属性名不一致的情况。

注意:resultType和resultMap不能同时使用。

3.列名和Java对象属性名称不一致解决方式 3.1 使用resultMap:自定义列名和属性名称对应关系

这个方法在上面讲解resultMap的时候就讲解了,可以直接看上面

3.2 使用resultType

使用列别名,让别名和Java对象属性名称一样

我们在dao接口中定义一个方法:

CustomObject selectById3(Integer id);

我们在mapper文件中写:


我们在测试类中进行测试

    @Test
    public void testSelectById3() {
        SqlSession session = MyBatisUtil.getSqlSession();
        StudentDao dao = session.getMapper(StudentDao.class);
        CustomObject co = dao.selectById2(1003);
        System.out.println(co);
        session.close();
    }

控制台输出:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/424264.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号