myBatisPlus-查询

根据 ID 查询

@Test
public void selectById() {
    User user = userMapper.selectById(1373101231285764097L);
    System.out.println(user);
}

多个 ID 批量查询

@Test
public void batchSelectById() {
    List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
    users.forEach(System.out::println);
}

简单条件查询

  • Map 中的 key 对应的是数据库中的列名
  • 例如数据库 user_id,实体类是 userId,这时 Map 的 key 需要填写 user_id
  • 你只需要把需要查询的条件添加到 Map 当中即可
@Test
public void selectByMap() {
    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put("name", "BNTang");

    List<User> users = userMapper.selectByMap(paramMap);
    users.forEach(System.out::println);
}

分页查询

MyBatis Plus 自带分页插件

使用 Mp 自带分页插件

首先需要配置分页插件,修改 Config.java 代码如下所示

/**
 * <p>
 * 配置分页插件
 * </p>
 */
@Bean
public PaginationInterceptor paginationInterceptor() {
    return new PaginationInterceptor();
}

编写测试分页代码如下

@Test
public void pageSelect() {
    // 创建 page 对象 参数1:当前页,参数2: 每页显示的记录数
    Page<User> page = new Page<>(2, 3);
    // 调用 mp 分页查询的方法, 调用 mp 分页查询过程中,底层会把分页查询到的数据封装到 page 对象里面
    userMapper.selectPage(page, null);
    // 通过 page 对象获取分页之后的一些数据信息如下
    System.out.println("当前页: " + page.getCurrent());
    System.out.println("每页数据: " + page.getRecords());
    System.out.println("每页显示记录数: " + page.getSize());
    System.out.println("总记录数: " + page.getTotal());
    System.out.println("总页数: " + page.getPages());
    System.out.println("是否有下一页: " + page.hasNext());
    System.out.println("是否有上一页: " + page.hasPrevious());
}

posted @ 2021-03-20 20:06  BNTang  阅读(6)  评论(0)    收藏  举报