默认按最新新增时间加载显示,默认每页显示50条,超过显示条数分页展示,支持切换显示条数。参照以上条件使用spring,springboot,MybatisPlus框架生成分页查询代码
时间: 2023-11-26 07:04:07 浏览: 83
Spring Boot+MybatisPlus使用JQuery DataTables表格插件展示数据、实现分页和模糊查询等功能
好的,以下是示例代码:
首先,在pom.xml文件中添加相关依赖:
```xml
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
```
接着,创建一个实体类,用于映射数据库表的数据:
```java
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("your_table_name")
public class YourEntity {
private Long id;
private String name;
private Integer age;
private String email;
}
```
然后,创建一个Mapper接口,用于定义数据库操作的方法:
```java
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface YourMapper extends BaseMapper<YourEntity> {
}
```
接下来,使用MyBatis Plus的分页插件,创建一个分页查询的方法:
```java
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class YourService {
@Autowired
private YourMapper yourMapper;
public IPage<YourEntity> getPage(Integer pageNum, Integer pageSize) {
return yourMapper.selectPage(new Page<>(pageNum, pageSize), null);
}
}
```
最后,在Controller中调用此方法,并返回分页查询结果:
```java
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class YourController {
@Autowired
private YourService yourService;
@GetMapping("/page")
public IPage<YourEntity> getPage(@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "50") Integer pageSize) {
return yourService.getPage(pageNum, pageSize);
}
}
```
这样,当访问 "/page" 接口时,就会返回分页查询的结果。其中,pageNum 和 pageSize 参数用于指定当前页码和每页显示条数,均有默认值。
阅读全文