以下是详细总结:
1. 查询操作(SELECT)
返回类型:
- 单条记录 → 实体类对象
- 多条记录 →
List<实体类>
- 统计查询 →
Integer
/Long
等基本类型
示例:
// 返回单个对象(查不到返回null)
User user = userMapper.selectById(1);
// 返回List集合(无数据时返回空集合,非null)
List<User> users = userMapper.selectList(queryWrapper);
// 返回统计数量
Long count = userMapper.selectCount(queryWrapper);
2. 插入操作(INSERT)
返回类型:
- 默认返回
int
→ 受影响的行数(通常为1或0) - 使用
@Options
可返回自增主键
示例:
// 返回受影响行数(通常1)
int rows = userMapper.insert(user);
// 获取自增ID(需在XML或注解配置)
@Options(useGeneratedKeys = true, keyProperty = "id")
int insert(User user); // 插入后user.getId()自动赋值为自增ID
3. 更新操作(UPDATE)
返回类型:
int
→ 受影响的行数(0表示未找到匹配记录)
示例:
// 返回更新的记录数(可能为0)
int rows = userMapper.updateById(user);
if (rows == 0) {
log.warn("更新失败,ID不存在");
}
4. 删除操作(DELETE)
返回类型:
int
→ 受影响的行数
示例:
// 返回删除的记录数(可能为0)
int rows = userMapper.deleteById(1);
5. 批量操作
返回类型:
int
→ 所有操作影响的总行数
示例:
// 批量插入(返回总插入行数)
int total = userMapper.insertBatchSomeColumn(list);
// 批量删除(返回总删除行数)
int deleted = userMapper.deleteBatchIds(Arrays.asList(1, 2, 3));
6. 特殊返回类型
(1) 返回Map
@MapKey("id") // 指定key字段
Map<Long, User> userMap = userMapper.selectMap(queryWrapper);
(2) 返回自定义DTO
List<UserDTO> dtos = userMapper.selectCustomDTOs(queryWrapper);
(3) 存储过程调用
Map<String, Object> params = new HashMap<>();
params.put("userId", 1);
userMapper.callProcedure(params);
// 通过params.get("outputParam")获取输出参数
总结表
操作类型 | 典型方法 | 返回值 | 说明 |
---|---|---|---|
查询 | selectById | 实体对象或null | 查不到返回null |
查询 | selectList | List<T> | 无数据返回空集合(非null) |
插入 | insert | int (受影响行数) | 通常为1 |
更新 | updateById | int (受影响行数) | 0表示未找到记录 |
删除 | deleteById | int (受影响行数) | 0表示未找到记录 |
批量操作 | deleteBatchIds | int (总行数) | 多条SQL影响的行数之和 |
统计 | selectCount | long | 符合条件的记录总数 |
最佳实践
-
插入操作:
- 使用
@Options
获取自增ID,而非依赖返回值。
- 使用
-
更新/删除:
- 检查返回值是否为0,判断操作是否生效。
-
查询:
- 使用
Optional
处理可能为null的单条查询结果:Optional<User> user = Optional.ofNullable(userMapper.selectById(1));
- 使用
-
批量操作:
- 考虑分批处理(如每批1000条)避免大事务。
通过理解这些返回类型,可以更安全地处理数据库操作结果!