Mybatis-Plus简单查询以及分页查询

mp实现简单查询和分页查询.png

Mybatis-Plus只对Mybatis做增强,即Mybatis原先的功能都可以使用。

1.根据id查询记录

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

2.通过多个id批量查询

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

3.简单的条件查询

通过map封装查询条件

@Test
public void testSelectByMap(){
    HashMap map = new HashMap<>();
    map.put("name", "Helen");
    map.put("age", 18);
    List users = userMapper.selectByMap(map);
    users.forEach(System.out::println);
}

注意:map中的key对应的是数据库中的列名。例如数据库user_id,实体类是userId,这时map的key需要填写user_id

4.分页

MyBatis Plus自带分页插件,只要简单的配置即可实现分页功能
(1)创建配置类

/**
 * 分页插件
 */
@Bean
public PaginationInterceptor paginationInterceptor() {
    return new PaginationInterceptor();
}

(2)测试selectPage分页
测试:最终通过page对象获取相关数据

@Test
public void testSelectPage() {
    Page page = new Page<>(1,5);
    userMapper.selectPage(page, null);
    page.getRecords().forEach(System.out::println);
    System.out.println(page.getCurrent());
    System.out.println(page.getPages());
    System.out.println(page.getSize());
    System.out.println(page.getTotal());
    System.out.println(page.hasNext());
    System.out.println(page.hasPrevious());
}

控制台sql语句打印:SELECT id,name,age,email,create_time,update_time FROM user LIMIT 0,5
(3)测试selectMapsPage分页:结果集是Map

@Test
public void testSelectMapsPage() {
    Page page = new Page<>(1, 5);
    IPage> mapIPage = userMapper.selectMapsPage(page, null);
    //注意:此行必须使用 mapIPage 获取记录列表,否则会有数据类型转换错误
    mapIPage.getRecords().forEach(System.out::println);
    System.out.println(page.getCurrent());
    System.out.println(page.getPages());
    System.out.println(page.getSize());
    System.out.println(page.getTotal());
    System.out.println(page.hasNext());
    System.out.println(page.hasPrevious());
}

你可能感兴趣的:(Mybatis-Plus简单查询以及分页查询)