Mybatis-Plus簡單查詢以及分頁查詢

mp實現(xiàn)簡單查詢和分頁查詢.png

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

1.根據(jù)id查詢記錄

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

2.通過多個id批量查詢

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

3.簡單的條件查詢

通過map封裝查詢條件

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

注意:map中的key對應(yīng)的是數(shù)據(jù)庫中的列名。例如數(shù)據(jù)庫user_id,實體類是userId,這時map的key需要填寫user_id

4.分頁

MyBatis Plus自帶分頁插件,只要簡單的配置即可實現(xiàn)分頁功能
(1)創(chuàng)建配置類

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

(2)測試selectPage分頁
測試:最終通過page對象獲取相關(guān)數(shù)據(jù)

@Test
public void testSelectPage() {
    Page<User> 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語句打?。篠ELECT id,name,age,email,create_time,update_time FROM user LIMIT 0,5
(3)測試selectMapsPage分頁:結(jié)果集是Map

@Test
public void testSelectMapsPage() {
    Page<User> page = new Page<>(1, 5);
    IPage<Map<String, Object>> mapIPage = userMapper.selectMapsPage(page, null);
    //注意:此行必須使用 mapIPage 獲取記錄列表,否則會有數(shù)據(jù)類型轉(zhuǎn)換錯誤
    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());
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容