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方法。
- 如果数据库字段有唯一约束,那么你再添加相同的数据,则无法添加成功,但如果没有唯一约束,程序上可能出现并发,添加到数据库可以成功,但再次查询时会因为返回多条数据而导致程序出现问题。
更多推荐

所有评论(0)