Problem
Spring Data REST ๋ entity type ์ name ์ ๊ธฐ๋ฐ์ผ๋ก endpoints ๋ฅผ ์์ฑํ๋ค.
๊ทธ๋ฌ๋, ์์ด๋ ๋งค์ฐ ํผ์ก์ค๋ฌ์ด ์ธ์ด์ด๊ธฐ ๋๋ฌธ์ ๊ฐํน โGoose, Geeseโ ์ ๊ฐ์ ๋ถ๊ท์นํ plural form ์ด ์กด์ฌํ๋ค. Spring Data REST ๋ ์ด๊ฒ๊น์ง ์ง์ํ์ง๋ ์๋๋ค.
๊ทธ๋ ๋ค๋ฉด ์ด์ ๊ฐ์ noun ์ ์ฌ์ฉํ ๋์๋, entity type ๊ณผ ๋ค๋ฅธ ๋จ์ด๋ก endpoint ๋ฅผ ์์ฑํ๊ณ ์ถ์ ๋์๋ ์ด๋ป๊ฒ ํด์ผ ํ ๊น?
Solution
@RepositoryRestResource(path="members")
public interface EmployeeRepository extends JpaRepository<Employee, Integer> {}์์ ๊ฐ์ด @RepositoryRestResource annotation ์ ์ฌ์ฉํ์ฌ explicit ํ๊ฒ endpoint name ์ ์ง์ ํ ์ ์๋ค.
Pagination
default ๋ก, Spring Data REST ๋ first 20 elements ๋ฅผ return ํ๋ค. ์ฆ, Page size ๋ 20 ์ธ ๊ฒ์ด๋ค.
http://localhost:8080/employees?page=0 ๊ณผ ๊ฐ์ด, URL ์์ ? ๋ค์ ๋ถ๋ key=value ํํ์ data ์ธ Query Parameter ๋ฅผ ์ฌ์ฉํ์ฌ different page ๋ฅผ navigate ํ ์ ์๋ค. page ๋ 0 ๋ถํฐ ์์ํ๋ค.
spring.data.rest.base-path, spring.data.rest.default-page-size, spring.data.rest.max-page-size ๋ฑ, spring.data.rest.* ์ application.properties file ์ configure ํ๋ ๊ฒ์ ํตํ์ฌ Pagination ์ ์ค์ ํ ์ ์๋ค. ๋ ์์ธํ ๋ด์ฉ์ Spring Document ์์ ํ์ธํ ์ ์๋ค.
Sorting
entity ์ property name ์ผ๋ก sorting ์ ์ํํ ์ ์๋ค. lastName ์ ๊ธฐ์ค์ผ๋ก sorting ์ ์ํ๋ฉด,
http://localhost:8080/employees?sort=lastName๊ณผ ๊ฐ์ด query parameter sort ๋ฅผ ์ฌ์ฉํ๊ณ , default ๋ ascending order ์ด๊ธฐ ๋๋ฌธ์,
http://localhost:8080/employees?sort=lastName,desc๋ฅผ ํตํ์ฌ descending order ๋ก๋ sorting ํ ์ ์๋ค. ๋ง์ฝ last name ์ ๊ธฐ์ค์ผ๋ก sorring ํ๊ณ , ๊ทธ ์์์ first name ์ผ๋ก sorting ํ๊ณ ์ถ๋ค๋ฉด,
http://localhost:8080/employees?sort=lastName,firstNamem,asclast name ์ ๋ด๋ฆผ์ฐจ์, ๊ทธ ๋ค์ first name ์ ์ค๋ฆ์ฐจ์์ด๋ผ๋ฉด,
http://localhost:8080/employees?sort=lastName,desc&sort=firstName,asc๊ณผ ๊ฐ์ด ์์ฑํ๋ฉด ๋๋ค.
Test - Configuration
๋จผ์ @RepositoryRestResource annotation ์ ํตํ์ฌ endpoint ๋ฅผ members ๋ก ๋ณ๊ฒฝํด๋ณด์.
response body ๋ฅผ ๋ณด๋ฉด, HATEOAS ์ ์ํ์ฌ page ์ ๋ํ meta-data ๋ ๊ฐ์ด ๋์ด์จ ๊ฒ์ ๋ณผ ์ ์๋ค. size ๊ฐ 20 ์ด๋ผ๋ ๊ฒ์ ์๊น ์ธ๊ธํ page size ๊ฐ default ๋ 20 ์ด๋ผ๋ ๊ฒ์ ์ฆ๋ช
ํ๋ค.
Test - Pagination
application.properties ์ spring.data.rest.default-page-size=3 ์ผ๋ก ์ค์ ํ๊ณ ๋ค์ request ๋ฅผ ๋ณด๋ด๋ฉด,
์์ ๊ฐ์ด size ๋ 3, totalElements ๋ 4 ์ด๋ฏ๋ก, totalPages ๊ฐ 2 ๊ฐ ๋ ๊ฒ์ ํ์ธํ ์ ์๋ค. ๋ํ first 3 elements ๊ฐ return ๋๋ฏ๋ก, query parameter ๋ฅผ ํตํ์ฌ page ๊ฐ์ navigation ์ ์ํํ ์ ์๋ค. ์๋๋ฉด ๋ค์๊ณผ ๊ฐ์ด first 4 elements ๋ก ๊ฐ์ ํ ์๋ ์๋ค.
http://localhost:8080/magic-api/members?page=0&size=4Test - Sorting
๋ง์ง๋ง์ผ๋ก Sorting ์ ๋ํ์ฌ test ํด๋ณด์. query parameter sort ๋ฅผ ์ด์ฉํ์ฌ firstName ์ ๊ธฐ์ค์ผ๋ก ์ค๋ฆ์ฐจ์ ์ ๋ ฌํ๋ฉด,
๊ณผ ๊ฐ์ด ๊ฒฐ๊ณผ๊ฐ ์ ๋์จ ๊ฒ์ ๋ณผ ์ ์๊ณ , firstName ์ด "Arne" ์ธ entity ๋ฅผ ํ๋ ๋ POST ํ๊ณ , last name ๋ ๊ฐ์ด sorting ์ ํฌํจ์ํค๋ฉด,
์์ ๊ฐ์ด ๋์ผํ first name ์ ๊ธฐ์ค์ผ๋ก ๋จผ์ sorting ํ๊ณ , ์ดํ์ ๊ฐ์ first name ์ ๋ํ์ฌ ๋ค์ last name ์ ๊ธฐ์ค์ผ๋ก sorting ํ ๊ฒฐ๊ณผ๋ฅผ ๋ณผ ์ ์๋ค.