Mybatis 返回 One 和 List 的區分

返回一個對象

官網示例:<T> T selectOne(String statement)數據庫

結果: 可能爲 null。apache

注: 使用返回一個對象時,若數據庫查詢結果超過一條 record,Mybatis 則拋出非檢查類異常 TooManyResultsException eg. : org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 2 證實查詢出兩條ui

返回一個 List

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

結果: 若是沒有返回值,那麼就是一個空的 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)
相關文章
相關標籤/搜索