Mybatis 返回 One 和 List 的区分

返回一个对象

官网示例:<T> T selectOne(String statement)

结果:
可能为 null。

注:
使用返回一个对象时,若数据库查询结果超过一条 record,Mybatis 则抛出非检查类异常 TooManyResultsException
eg. : org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 2
证明查询出两条

返回一个 List

官网示例:<E> List<E> selectList(String statement)

结果:
如果没有返回值,那么就是一个空的 list,不会出现 null 的情况,所以使用时不用进行判空,直接循环处理即可。

官网对接口定义的解释:

The difference between selectOne and selectList is only in that selectOne must return exactly one object or null (none). If any more than one, an exception will be thrown. If you don't' know how many objects are expected, use selectList. If you want to check for the existence of an object, you're better off returning a count (0 or 1). The selectMap is a special case in that it is designed to convert a list of results into a Map based on one of the properties in the resulting objects. Because not all statements require a parameter, these methods are overloaded with versions that do not require the parameter object.
The value returned by the insert, update and delete methods indicate the number of rows affected by the statement.

<T> T selectOne(String statement)
<E> List<E> selectList(String statement)
<K,V> Map<K,V> selectMap(String statement, String mapKey)
int insert(String statement)
int update(String statement)
int delete(String statement)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容