mybatis判断集合为空
时间: 2024-11-12 19:46:35 浏览: 31
在MyBatis中,判断一个查询结果集(List或Map)是否为空,通常是通过条件语句或者自定义的ResultType来完成。以下是几种常见的方法:
1. **直接比较大小**:
```sql
SELECT * FROM table WHERE condition IF NULL THEN 'true' ELSE 'false'
```
或者在Mapper XML文件中:
```xml
<if test="collection == null || collection.isEmpty()">
<!-- do something if empty -->
</if>
```
2. **使用isEmpty()方法**:
MyBatis默认会将查询结果转化为List,所以可以直接使用Java的List接口的isEmpty()方法检查。
```java
List<YourEntity> entities = sqlSession.selectList("your_select_statement");
if (entities.isEmpty()) {
// handle the case when list is empty
}
```
3. **自定义ResultType**: 创建一个专门的类(如EmptyResult),并设置为ResultType,当结果集为空时,返回该类实例而不是普通的结果集。
```java
@Result(type=EmptyResult.class)
List<YourEntity> selectWhenEmpty();
```
然后在EmptyResult类中返回一个表示空的标志。
4. **使用foreach标签遍历**:
避免了硬编码判断,如果list不为空则循环一次。
```xml
<select id="your_id" resultType="YourEntity">
...
</select>
<if test="!resultItems.isEmpty()">
<!-- iterate over the items in the list -->
<foreach item="item" index="index" collection="resultItems">
...
</foreach>
</if>
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![xml](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)