mybatis select查询,无记录时list和entity返回值

本文探讨了在SpringBoot环境中使用MyBatis进行数据库操作的细节,包括配置、注解使用及返回值处理。特别关注了@Select注解在不同场景下的行为,如返回List和实体对象的区别。

测试环境

  • springboot:1.5.4-RELEASE
  • mybatis:3.4.1
  • Mybatis-spring:1.3.0

select list

  • SQL语句

        @Select("select * from order where uid=#{uid}")
        List<Order> selectList(@Param("uid") long uid);
    
  • Select result 为List的话,如果没有查询到相关结果,会返回new ArrayList

  • 判断为空不能用==null,可以使用CollectionUtils.isEmpty()方法

  • 源码分析

    Spring集成Mybatis,最终会走org.apache.ibatis.executor.resultset.DefaultResultSetHandler的handleResultSets(Statement stmt)方法,该方法中,会先new ArrayList,当查询结果有值的话,利用查询结果填充该list

select list源码

select entity

  • sql语句:与list的完全相同,只是返回值不同

        @Select("select * from order where uid=#{uid}")
        Order selectList(@Param("uid") long uid);
    
  • Select result为实体类的话,如果没有查询到结果,会返回null

  • 判断为空,用==null

  • 源码分析

    如下图,返回实体类的话,会走org.apache.ibatis.session.defaults.DefaultSqlSession的selectOne方法,该方法内部调用selectList。当list为空的时候,会直接返回null。所以在查询不到结果时,会返回null

select entity源码

结论

  • select list,如果为空,则返回空的list[]
  • select entity,如果为空,则返回null
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值