springboot鍒嗛〉鏌ヨ鐨勬柟娉曟湁鍝簺
鍦⊿pring Boot涓紝鍙互浣跨敤浠ヤ笅鏂规硶鏉ュ疄鐜板垎椤垫煡璇細
- 浣跨敤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);
}
}
- 浣跨敤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>
相关问答