springboot " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

springboot鍒嗛〉鏌ヨ鐨勬柟娉曟湁鍝簺

扬州沐宇科技
2024-03-13 15:14:55
springboot

鍦⊿pring Boot涓紝鍙互浣跨敤浠ヤ笅鏂规硶鏉ュ疄鐜板垎椤垫煡璇細

  1. 浣跨敤Spring Data JPA鐨?code>Pageable鎺ュ彛鍜?code>Page瀵硅薄鏉ュ疄鐜板垎椤垫煡璇€傚湪Repository鏂规硶涓紝鍙互瀹氫箟涓€涓甫鏈?code>Pageable鍙傛暟鐨勬煡璇㈡柟娉曪紝骞惰繑鍥?code>Page瀵硅薄銆?/li>
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
    Page<User> findAll(Pageable pageable);
}

鍦⊿ervice鎴朇ontroller涓紝鍙互閫氳繃璋冪敤Repository鐨勬煡璇㈡柟娉曟潵杩涜鍒嗛〉鏌ヨ锛屽苟鑾峰彇鍒板垎椤电粨鏋滐細

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public Page<User> findAllUsers(int page, int size) {
        PageRequest pageable = PageRequest.of(page, size);
        return userRepository.findAll(pageable);
    }
}
  1. 浣跨敤Spring Data JPA鐨?code>@Query娉ㄨВ鍜孞PQL璇彞鏉ュ疄鐜板垎椤垫煡璇€傚彲浠ュ湪Repository鎺ュ彛涓畾涔夊甫鏈?code>@Query娉ㄨВ鐨勬煡璇㈡柟娉曪紝骞跺湪JPQL璇彞涓娇鐢?code>LIMIT鍜?code>OFFSET鏉ラ檺鍒舵煡璇㈢粨鏋滅殑鏁伴噺鍜屽亸绉婚噺銆?/li>
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface UserRepository extends JpaRepository<User, Long> {

    @Query("SELECT u FROM User u")
    Page<User> findAllUsers(Pageable pageable);
}

鍦⊿ervice鎴朇ontroller涓紝鍚屾牱鍙互閫氳繃璋冪敤Repository鐨勬煡璇㈡柟娉曟潵杩涜鍒嗛〉鏌ヨ锛屽苟鑾峰彇鍒板垎椤电粨鏋溿€?/p>

浠ヤ笂鏄袱绉嶅父鐢ㄧ殑Spring Boot鍒嗛〉鏌ヨ鏂规硶锛屾牴鎹叿浣撶殑涓氬姟闇€姹傚拰鍠滃ソ鍙互閫夋嫨閫傚悎鐨勬柟娉曟潵瀹炵幇鍒嗛〉鏌ヨ銆?/p>

扫码添加客服微信