springboot mysql分页查询
时间: 2023-10-12 09:14:21 浏览: 83
以下是使用Spring Boot和MySQL进行分页查询的示例代码:
1. 添加Maven依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
```
2. 配置数据源
在application.properties文件中添加以下配置:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/db_name?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
3. 创建实体类
创建一个实体类,例如User:
```java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
// getter and setter
}
```
4. 创建Repository接口
创建一个Repository接口,例如UserRepository:
```java
public interface UserRepository extends JpaRepository<User, Long> {
Page<User> findAll(Pageable pageable);
}
```
5. 创建Controller
创建一个Controller,例如UserController:
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public Page<User> getUsers(Pageable pageable) {
return userRepository.findAll(pageable);
}
}
```
6. 测试分页查询
启动应用程序并访问http://localhost:8080/users?page=0&size=10&sort=id,asc,您将获取第1页的10个用户,按id升序排列。
您可以通过更改参数page和size来获取其他页面和数量。
以上是使用Spring Boot和MySQL进行分页查询的示例代码。
阅读全文
相关推荐


















