MyBatis学习笔记四

MyBatis输出结果

mybatis执行了sql语句,得到java对象。

1、resultType

resultType: 执行 sql 得到 ResultSet 转换的类型,使用类型的完全限定名或别名。 注意如果返回的是集合,那应该设置为集合包含的类型,而不是集合本身。resultType 和 resultMap,不能同时使用。
resultType结果类型, 指sql语句执行完毕后, 数据转为的java对象, java类型是任意的。
resultType结果类型的值

  1. 类型的全限定名称
  2. 类型的别名, 例如 java.lang.Integer别名是int

1.1 简单类型

接口方法:

int countStudent();

mapper 文件:

    <select id="countStudent" resultType="java.lang.Integer">
        select count(*) from student
    </select>

测试:

    @Test
    public void countStudent() {
   
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        int countStudent = dao.countStudent();
        System.out.println("学生总人数------->" + countStudent);
        sqlSession.close();
    }

在这里插入图片描述

1.2 对象类型

接口方法:

Student selectStudentById(Integer id);

mapper 文件:

    <select id="selectStudentById" resultType="com.b0kuwa.entity.Student">
        select * from student where id = #{id}
    </select>

框架的处理: 使用构造方法创建对象。调用 setXXX 给属性赋值。
Student student = new Student();
在这里插入图片描述
注意: Dao 接口方法返回是集合类型,需要指定集合中的类型,不是集合本身。
在这里插入图片描述
在这里插入图片描述

1.3 Map

sql 的查询结果作为 Map 的 key 和 value。推荐使用 Map<Object,Object>。
注意:Map 作为接口返回值,sql 语句的查询结果最多只能有一条记录。大于一条记录是错误。
接口方法:

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

mapper 文件:

    <select id="selectMapById" resultType="java.util.HashMap">
        select * from student where id = #{studentId}
    </select>

测试方法:

    @Test
    public void selectMapById() {
   
        SqlSess
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值