一、基础方式:注入 Mapper 操作数据库
1.1 前提:Mapper 必须继承 BaseMapper
这是整个 MyBatis-Plus 能力的入口。只要 Mapper 接口继承了 BaseMapper<T>,MyBatis-Plus 就会自动注入针对泛型实体 T 的基础 CRUD 方法,无需写任何 XML。
// Mapper 接口
@Mapper
public interface UserMapper extends BaseMapper<User> {
// BaseMapper 已提供基础方法,这里只写自定义 SQL
List<UserVO> selectUserWithRole(@Param("roleId") Long roleId);
}
对应实体类:
@Data
@TableName("user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String username;
private String email;
private Integer status;
private LocalDateTime createTime;
}
1.2 在 Service 实现类中注入 Mapper
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
// 通过 mapper 方法操作数据库
public User findById(Long id) {
return userMapper.selectById(id);
}
public void createUser(User user) {
userMapper.insert(user);
}
public void deleteUser(Long id) {
userMapper.deleteById(id);
}
}
1.3 BaseMapper 核心方法一览
| 方法 | 说明 |
|---|---|
insert(T entity) |
插入一条记录 |
deleteById(Serializable id) |
按主键删除 |
deleteByMap(Map<String, Object> map) |
按字段条件删除 |
delete(Wrapper<T> wrapper) |
按 Wrapper 条件删除 |
updateById(T entity) |
按主键更新(null 字段跳过) |
update(T entity, Wrapper<T> wrapper) |
按条件更新 |
selectById(Serializable id) |
按主键查询 |
selectBatchIds(Collection ids) |
批量主键查询 |
selectByMap(Map<String, Object> map) |
按字段条件查询 |
selectOne(Wrapper<T> wrapper) |
按条件查询单条 |
selectCount(Wrapper<T> wrapper) |
按条件查询数量 |
selectList(Wrapper<T> wrapper) |
按条件查询列表 |
selectPage(IPage<T> page, Wrapper<T> wrapper) |
BaseMapper 分页(返回 IPage<T>) |
二、条件构造器:Wrapper
2.1 Wrapper 的本质与作用
Wrapper 是 MyBatis-Plus 提供的条件构造器,独立于 IService 和 BaseMapper,本质是用 Java 代码动态拼接 SQL 的 WHERE 条件,避免手写 XML。
Wrapper 与各层的关系:
Wrapper(条件构造器)
├── 作为参数传入 BaseMapper 方法 ← 不继承 IService 时
├── 作为参数传入 IService 方法 ← 继承 IService 时
└── 作为链式查询的底层实现 ← lambdaQuery() 底层也是 Wrapper
2.2 Wrapper 类型体系
AbstractWrapper
├── QueryWrapper<T> ← 字符串字段名,存在拼错风险
├── LambdaQueryWrapper<T> ← 方法引用字段名,编译期检查,推荐
├── UpdateWrapper<T> ← 更新条件构造
└── LambdaUpdateWrapper<T>← Lambda 版本更新,推荐
2.3 LambdaQueryWrapper 常用方法
LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
// 等于
.eq(User::getStatus, 1)
// 不等于
.ne(User::getStatus, 0)
// 大于 / 大于等于
.gt(User::getAge, 18)
.ge(User::getAge, 18)
// 小于 / 小

2万+

被折叠的 条评论
为什么被折叠?



