Mybatis(五)Mybatis 的 selectOne 和 selectList 没有数据返回时的问题讨论

1、使用mybatis的selectList方法,如果数据表中没有数据返回,则返回空集合[ ],而不会返回null,这是mybatis作的封装

    @Override
    public List<ContactInfoEntity> getContactInfoListByRegistId(Long registId) {
        return getSqlSession().selectList("ContactInfo.getContactInfoListByRegistId", registId);
    }

2、使用mybatis的selectOne方法,如果数据表中没有数据返回,则返回null

    @Override
    public CustomerEntity getCustomerByCustomerNo(String customerNo) {
        return (CustomerEntity) getSqlSession().selectOne("Customer.getCustomerByCustomerNo", customerNo);
    }

3、使用mybatis的selectOne方法,如果返回多条数据,则会抛出异常,而不是返回多条数据的第一条数据,看底层源码可知

public Object selectOne(String statement, Object parameter) {
    // Popular vote was to return null on 0 results and throw exception on too many.
    List list = selectList(statement, parameter);
    if (list.size() == 1) {
      return list.get(0);
    } else if (list.size() > 1) {
      throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
    } else {
      return null;
    }
  }

讨论:

  • 数据库表字段如果有唯一约束,在mybatis中使用selectOne方法;
  • 数据库表字段如果没有唯一约束,即使在业务逻辑上此字段时唯一的,但还是建议使用selectList方法。
  • 如果数据库字段有唯一约束,那么你再添加相同的数据,则无法添加成功,但如果没有唯一约束,程序上可能出现并发,添加到数据库可以成功,但再次查询时会因为返回多条数据而导致程序出现问题。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值