Spring boot 数据访问及分页
时间: 2024-03-21 13:40:22 浏览: 26
Spring Boot提供了许多数据访问的方式,包括JPA、Hibernate、MyBatis、JDBC等。其中,JPA是最常用的一种。以下是一个使用Spring Data JPA实现数据访问和分页的示例:
1. 添加依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
```
2. 配置数据源
在application.properties文件中添加以下配置:
```
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop
```
3. 定义实体类
定义一个实体类,例如:
```
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private Integer age;
// 省略getter和setter方法
}
```
4. 定义数据访问接口
定义一个数据访问接口,例如:
```
public interface UserRepository extends JpaRepository<User, Long> {
}
```
5. 实现分页
在控制器中实现分页,例如:
```
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public Page<User> getUsers(@RequestParam(defaultValue = "0") Integer pageNo,
@RequestParam(defaultValue = "10") Integer pageSize) {
Pageable pageable = PageRequest.of(pageNo, pageSize);
return userRepository.findAll(pageable);
}
}
```
以上代码中,`findAll(pageable)`方法将返回一个Page对象,其中包含请求的页码和每页大小的数据。
6. 测试
使用浏览器或Postman等工具访问http://localhost:8080/users,将会返回一个Page对象,其中包含请求的页码和每页大小的数据。
以上就是Spring Boot数据访问及分页的实现方法。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)