以下是一个使用 Spring Boot 实现分页查询的示例代码:
首先,创建一个实体类 User :
package com.example.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
}
创建数据访问接口 UserRepository :
package com.example.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.example.entity.User;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.name LIKE %:name%")
Page<User> findByNameLike(@Param("name") String name, Pageable pageable);
}
创建服务类 UserService :
package com.example.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.example.entity.User;
import com.example.repository.UserRepository;
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public Page<User> getUsersByName(String name, int page, int size) {
Pageable pageable = PageRequest.of(page, size);
return userRepository.findByNameLike(name, pageable);
}
}
创建控制器 UserController :
package com.example.controller;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.service.UserService;
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public Page<User> getUsersByName(@RequestParam("name") String name,
@RequestParam("page") int page,
@RequestParam("size") int size) {
return userService.getUsersByName(name, page, size);
}
}
请确保在项目的配置文件(如 application.properties 或 application.yml )中配置了数据库相关的连接信息。
以上示例代码实现了根据名称进行分页查询用户的功能。