QueryMethod(JPA)๋ฅผ ๋ณด๊ณ ... ๋๋ ์์ฒญ๋ ์ ๋ ์นด์๋ค...
์ด๋ ๊ฒ ์์ฒญ๋๊ฒ ์ ๊ธฐํ ๊ธฐ๋ฅ์ด ์๋ค๋ ๊ฒ์ด ๋๋ฌด๋๋ฌด ์ ๊ธฐํ๋ค.
์ด๋ฆ ๊ทธ๋๋ก Query ๋ฌธ์ผ๋ก Method๋ฅผ ๋ง๋ค์ด์ ์ฌ์ฉํ๋ ๊ฒ์ด๋ค.
public List<PostResponseDto> getAllPosts() {
return postRepository.findAll()
.stream()
.map(PostResponseDto::new)
.toList();
}
์ด๋ ๊ฒ ๋ชจ๋ ๊ฒ์๊ธ์ ์กฐํํ๋ method๊ฐ ์๋ค.
์ฌ๊ธฐ์๋ ListCrudRepository์์ ์ ๊ณตํ๋ findAll() ์ด๋ผ๋ method๋ฅผ ์ฌ์ฉํ์๋ค.
ํ์ง๋ง ์ด๋ ๊ฒ ํ๊ฒ ๋๋ฉด ๋ด๊ฐ ์ํ๋ ์์๋๋ก ์กฐํ๋ฅผ ํ ์ ์๋ค.
๊ฒ์๊ธ์ ์์ฑํ ์๊ฐ์ ๋ด๋ฆผ์ฐจ์์ผ๋ก ์กฐํ๋ฅผ ํ๊ณ ์ถ๋ค.
public interface PostRepository extends JpaRepository<Post, Long>{
}
JpaRepository๋ฅผ ์์๋ฐ์ PostRepository interface๋ฅผ ๊ฐ์ง๊ณ ์๋ค.
์ฌ๊ธฐ์ JpaRepository ์์ ์๋ ์์ฃผ์์ฃผ ์ ๊ธฐํ ๊ธฐ๋ฅ์ ์ฌ์ฉํ ์ ์์๋ค.
QueryMethod
Query๋ฅผ ์์ฑํ๋ฏ method๋ฅผ ์์ฑํ๋ฉด ๋๋ค.
List<Post> findByOrderByCreatedAtDesc();
// ์ฐพ๋๋ค -> ์ ๋ ฌํ๋ค -> createdAt ๊ธฐ์ค์ผ๋ก -> ๋ด๋ฆผ์ฐจ์ํ๋ค.
์ด๋ ๊ฒ method๋ฅผ ๋ง๋ค๋ฉด findAll() ๋์ findByOrderByCreatedAtDesc() ์ด๋ ๊ฒ ์ฐ๋ฉด ๋๋ค..
๋ค์ ๋ด๋ ๋๋ฌด ์ ๊ธฐํ๋ค.
public List<PostResponseDto> getAllPosts() {
return postRepository.findByOrderByCreatedAtDesc()
.stream()
.map(PostResponseDto::new)
.toList();
}