Intro
์๋ ํ์ธ์. ์ด๋ฒ ์๊ฐ์๋ spring boot ์์ JPA์ pageable ํ์ฉํ sort ์ ๋ ฌ ๊ตฌํ ๋ฐฉ๋ฒ์ ๋ํด ์์๋ณด๋๋ก ํ๊ฒ ์ต๋๋ค. user ๋ฐ์ดํฐ๊ฐ ์๋ค๋ ๊ฐ์ ํ์ ์งํํด๋ณด๋๋ก ํ๊ฒ ์ต๋๋ค.
1. User ์ํฐํฐ ์ ์
User ์ํฐํฐ์๋ id, name, email, createdDate ๋ฑ์ ํ๋๊ฐ ์๋ค๊ณ ๊ฐ์ ํฉ๋๋ค.
@Entity
data class User(
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long,
val name: String,
val email: String,
@CreatedDate
val createdDate: LocalDateTime
)
2. UserRepository ์ธํฐํ์ด์ค ์ ์
User ๋ฐ์ดํฐ๋ฅผ ํ์ด์ง๊ณผ ์ ๋ ฌ๋ก ์กฐํํ๊ธฐ ์ํด JpaRepository๋ฅผ ์์ํ UserRepository ์ธํฐํ์ด์ค๋ฅผ ์ ์ํฉ๋๋ค. JpaRepository๋ ํ์ด์ง๊ณผ ์ ๋ ฌ์ ์๋์ผ๋ก ์ง์ํฉ๋๋ค. findAll(Pageable pageable) ๋ฉ์๋๋ฅผ ํตํด ํ์ด์ง ๋ฐ ์ ๋ ฌ๋ ๋ฐ์ดํฐ๋ฅผ ์ฝ๊ฒ ์กฐํํ ์ ์์ต๋๋ค.
interface UserRepository : JpaRepository<User, Long>
3. UserController์์ Pageable๊ณผ Sort ์ฌ์ฉ
3.1. ๊ธฐ๋ณธ์ ์ธ ํ์ด์ง๊ณผ ์ ๋ ฌ
Pageable ๊ฐ์ฒด๋ URL ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ์์ page, size, sort๋ฅผ ์๋์ผ๋ก ์ฒ๋ฆฌํ ์ ์์ต๋๋ค. ์ ์ฝ๋์์๋ pageable ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ์ฌ findAll(pageable)์ ํธ์ถํ๊ณ , Spring Data JPA๊ฐ ์ ๊ณตํ๋ ํ์ด์ง๊ณผ ์ ๋ ฌ ๊ธฐ๋ฅ์ ์๋์ผ๋ก ์ ์ฉํฉ๋๋ค.
@RestController
@RequestMapping("/users")
class UserController(private val userRepository: UserRepository) {
@GetMapping
fun getUsers(
pageable: Pageable // Spring Data JPA๊ฐ ์๋์ผ๋ก ์ฒ๋ฆฌํ๋ Pageable ๊ฐ์ฒด
): ResponseEntity<Page<User>> {
val users = userRepository.findAll(pageable) // pageable์ ์ฌ์ฉํ์ฌ ํ์ด์ง๊ณผ ์ ๋ ฌ ์ ์ฉ
return ResponseEntity.ok(users)
}
}
3.2. URL ์์
๋ค์๊ณผ ๊ฐ์ URL๋ก ์์ฒญ์ ๋ณด๋ผ ์ ์์ต๋๋ค. Spring Boot๋ ์๋์ผ๋ก Pageable ๊ฐ์ฒด๋ฅผ ๊ตฌ์ฑํ๊ณ findAll(pageable)์ ์ ๋ฌํฉ๋๋ค. ์ด๋, name ํ๋๋ฅผ ๊ธฐ์ค์ผ๋ก ์ค๋ฆ์ฐจ์ ์ ๋ ฌ๋ User ๋ฐ์ดํฐ๋ฅผ ์ฒซ ๋ฒ์งธ ํ์ด์ง์์ 10๊ฐ์ฉ ๋ฐํํฉ๋๋ค.
GET /users?page=0&size=10&sort=name,asc
- page=0: ์ฒซ ๋ฒ์งธ ํ์ด์ง (0๋ถํฐ ์์)
- size=10: ํ ํ์ด์ง์ 10๊ฐ์ ๋ฐ์ดํฐ
- sort=name,asc: name ํ๋๋ฅผ ๊ธฐ์ค์ผ๋ก ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
3.3. ์ฌ๋ฌ ํ๋๋ฅผ ๊ธฐ์ค์ผ๋ก ์ ๋ ฌํ๊ธฐ
์ฌ๋ฌ ๊ฐ์ ํ๋๋ฅผ ๊ธฐ์ค์ผ๋ก ์ ๋ ฌํ๋ ค๋ฉด sort ํ๋ผ๋ฏธํฐ์ ์ผํ๋ก ๊ตฌ๋ถ๋ ์ ๋ ฌ ๊ธฐ์ค์ ์ ๋ฌํ๋ฉด ๋ฉ๋๋ค. ์๋ฅผ ๋ค์ด, name ํ๋๋ฅผ ์ค๋ฆ์ฐจ์์ผ๋ก, createdDate ํ๋๋ฅผ ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌํ๋ ค๋ฉด ๋ค์๊ณผ ๊ฐ์ด URL์ ์์ฑํ ์ ์์ต๋๋ค.
GET /users?page=0&size=10&sort=name,asc,createdDate,desc
3.4. PageRequest์ Sort๋ฅผ ์ฌ์ฉํ์ฌ ์ง์ ์ค์
ํด๋ผ์ด์ธํธ์์ ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ๋ก ์ ๋ ฌ ๊ธฐ์ค์ ๋ณด๋ด์ง ์๊ณ , ์๋ฒ์์ ์ง์ PageRequest์ Sort๋ฅผ ์ค์ ํ ์๋ ์์ต๋๋ค.
@GetMapping("/users/custom-sort")
fun getUsersWithCustomSort(): ResponseEntity<Page<User>> {
// ๊ธฐ๋ณธ์ ์ผ๋ก name์ ์ค๋ฆ์ฐจ์, createdDate๋ฅผ ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌ
val sort = Sort.by(Sort.Order.asc("name"), Sort.Order.desc("createdDate"))
val pageable = PageRequest.of(0, 10, sort) // ์ฒซ ํ์ด์ง, 10๊ฐ์ฉ, ์ ๋ ฌ ๊ธฐ์ค ์ค์
val users = userRepository.findAll(pageable)
return ResponseEntity.ok(users)
}