前言
Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。 链接: Mybatis-Plus官网地址
准备数据库表
执行SQL文件创建表添加数据
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
配置文件
配置数据源:
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8
username: root
password: admin
driver-class-name: com.mysql.jdbc.Driver
实体类代码
package com.gavin.boot.domain;
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
mapper接口代码
package com.gavin.boot.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gavin.boot.domain.User;
import java.util.List;
@Mapper
public interface UserMapper extends BaseMapper<User> {
List<User> selectPageVo(IPage<User> page);
}
service接口代码
package com.gavin.boot.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gavin.boot.domain.User;
public interface UserService extends IService<User> {
}
service实现类代码
package com.gavin.boot.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gavin.boot.domain.User;
import com.gavin.boot.mapper.UserMapper;
import com.gavin.boot.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
controller类代码
实现User表的分页查询
package com.gavin.boot.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gavin.boot.domain.User;
import com.gavin.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/getUserList")
@ResponseBody
public List<User> getUserList() {
Page<User> userPage = new Page<>();
userPage.setCurrent(1);
userPage.setSize(2);
Page<User> page = userService.page(userPage);
List<User> list = page.getRecords();
return list;
}
}
启动项目测试
直接访问接口:http://localhost:8080/getUserList 可以看到返回的数据是第一页的两条数据
总结
以上就是Mybatis-Plus获取分页数据的操作,其它功能后面有时间了再继续更新。
|