springboot实现分页查询

以下是一个使用 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 )中配置了数据库相关的连接信息。

以上示例代码实现了根据名称进行分页查询用户的功能。

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值