Mybatis Plus 查询数据(图文讲解)
大家好,我是小哈。
本小节中,我们将学习如何通过 Mybatis Plus 查询数据库表中的数据。
表结构
在前面小节中,我们已经定义好了一个用于测试的用户表, 执行脚本如下:
DROP TABLE IF EXISTS user; CREATE TABLE `user` ( `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', `name` varchar(30) NOT NULL DEFAULT '' COMMENT '姓名', `age` int(11) NULL DEFAULT NULL COMMENT '年龄', `gender` tinyint(2) NOT NULL DEFAULT 0 COMMENT '性别,0:女 1:男', PRIMARY KEY (`id`) ) COMMENT = '用户表';
定义实体类
定义一个名为 User
实体类:
@TableName("user")
public class User {
/** * 主键 ID, @TableId 注解定义字段为表的主键,type 表示主键类型,IdType.AUTO 表示随着数据库 ID 自增 */ @TableId(type = IdType.AUTO) private Long id; /** * 姓名 */ private String name; /** * 年龄 */ private Integer age; /** * 性别 */ private Integer gender; }
不明白 Mybatis Plus 实体类注解的小伙伴,可参考前面小节 , 有详细解释。
开始查询数据
Mybatis Plus 对 Mapper 层和 Service 层都将常见的增删改查操作封装好了,只需简单的继承,即可轻松搞定对数据的增删改查,本文重点讲解查询相关的部分。
Mapper 层
定义一个 UserMapper
, 让其继承自 BaseMapper
:
public interface UserMapper extends BaseMapper<User> { }
然后,注入 Mapper :
@Autowired
private UserMapper userMapper;
BaseMapper
提供的查询相关的方法如下:
解释一下每个方法的作用:
// 根据 ID 查询
T selectById(Serializable id);
// 通过 Wrapper 组装查询条件,查询一条记录
T selectOne(Wrapper<T> queryWrapper);
// 查询(根据ID 批量查询)
List<T> selectBatchIds(Collection<? extends Serializable> idList);
// 通过 Wrapper 组装查询条件,查询全部记录
List<T> selectList(Wrapper<T> queryWrapper);
// 查询(根据 columnMap 来设置条件) List<T> selectByMap(Map<