您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,使用DAO(数据访问对象)实现分页查询通常涉及以下步骤:
public class User {
private int id;
private String name;
private String email;
// 构造函数、getter和setter方法省略
}
JpaRepository
或CrudRepository
的接口,用于定义基本的数据库操作:import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User, Integer> {
}
Pageable
参数。首先,需要在方法签名中添加Pageable
参数:import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
public interface UserRepository extends CrudRepository<User, Integer> {
Page<User> findAll(Pageable pageable);
}
UserRepository
并实现分页查询方法:import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Page<User> findAllUsers(int page, int size) {
Pageable pageable = PageRequest.of(page, size);
return userRepository.findAll(pageable);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public Page<User> findAllUsers(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
return userService.findAllUsers(page, size);
}
}
现在,你可以通过发送包含page
和size
参数的GET请求到/users
端点来执行分页查询。例如,要获取第1页上的前10个用户,可以发送以下请求:
GET /users?page=0&size=10
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。