์ฝ๋๋ฅผ ๋ณด๋ค๊ฐ Example<T> ์ธํฐํ์ด์ค๋ฅผ ํ์ฉํ ๊ฒฝ์ฐ๊ฐ ์์๋ค.
Example<T>๋ฅผ ์ธ์ ์ฌ์ฉํ๊ณ , ์ ์ฌ์ฉํ๋์ง ์์๋ณด์.
Example<T> ์ธํฐํ์ด์ค๋ ?
Spring Data Core์์ ์ ๊ณตํ๋ ๊ฒ์ผ๋ก, QBE(Query By Example)์ ์ง์ํ๋ ๊ธฐ๋ฅ์ด๋ค.
๊ฐ์ฒด ์์ฒด๋ฅผ ์ฟผ๋ฆฌ ์กฐ๊ฑด์ผ๋ก ํ์ฉํ์ฌ ๊ฐ๋จํ ๊ฒ์์ ์ํํ ์ ์๋ค.
์ฃผ์ ๊ฐ๋
- ๋๋ฉ์ธ ๊ฐ์ฒด(์ํฐํฐ) ์์ฒด๋ฅผ ๊ฒ์ ์กฐ๊ฑด์ผ๋ก ํ์ฉ
- Null ๊ฐ์ ๋ฌด์ (ํ๋ ๊ฐ์ด ์๋ ๊ฒ๋ง ๊ฒ์ ์กฐ๊ฑด์ผ๋ก ์ฌ์ฉ)
- ๋์ ์ฟผ๋ฆฌ ์์ฑ ๊ฐ๋ฅ
- ๋ณ๋์ JPQL์ด๋ SQL์ ์์ฑํ ํ์ ์์
๐ ๊ฐ๋จํ ๊ฒ์์์๋ ์ ์ฉํ๊ฒ ์ผ๋.. ์ค๋ฌด์์๋ ๋ณต์กํ ๊ฒ์์ด ๋ ๋ง์ด ๋๋ฌธ์ ๊ทธ๋ฅ ์ ๋ฐ ๊ธฐ๋ฅ์ด ์๊ตฌ๋ ์ ๋๋ง ์์๋ ๋ ๊ฒ ๊ฐ๋ค.
์ฌ์ฉ ์์
User probe = new User();
probe.setName("Alice"); // ์ด๋ฆ์ด Alice์ธ ์ฌ์ฉ์ ๊ฒ์
Example<User> example = Example.of(probe);
name ํ๋๋ง ๊ฐ์ด ์์ผ๋ฏ๋ก, ํด๋น ํ๋๋ง ๊ฒ์ ์กฐ๊ฑด์ผ๋ก ์ฌ์ฉ๋จ
ExampleMatcher
Example์ ์์ ์ผ์น ๋น๊ต๋ฅผ ์ํํ์ง๋ง, ExampleMatcher๋ฅผ ์ฌ์ฉํ๋ฉด ์ผ๋ถ ํ๋๋ฅผ ๋ฌด์ํ๊ฑฐ๋ ๋ฌธ์์ด ๊ฒ์์ ์ ์ฐํ๊ฒ ๋ง๋ค ์ ์๋ค.
// 1. ๊ฒ์ ์กฐ๊ฑด ๊ฐ์ฒด ์์ฑ
User probe = new User();
probe.setName("alice"); // ๋์๋ฌธ์ ๊ตฌ๋ถ ์์ด ๊ฒ์
probe.setAge(25); // ๋์ด 25์ธ์ธ ๊ฒฝ์ฐ๋ง ๊ฒ์
// 2. ExampleMatcher ์ค์ (๋์๋ฌธ์ ๋ฌด์ & ๋ถ๋ถ ๊ฒ์)
ExampleMatcher matcher = ExampleMatcher.matching()
.withIgnoreCase("name") // name ํ๋๋ ๋์๋ฌธ์ ๋ฌด์
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING); // ๋ถ๋ถ ๊ฒ์ (like '%alice%')
// 3. Example ์์ฑ
Example<User> example = Example.of(probe, matcher);
List<User> users = userRepository.findAll(example);
๐ ์ด๋ฆ์ alice๊ฐ ํฌํจ๋๋ฉด์ ๋์ด๊ฐ 25์ธ ์ฌ์ฉ์ ์กฐํ
ํ๊ณ์
- AND ์กฐ๊ฑด๋ง ์ง์ (OR ์กฐ๊ฑด ์ง์ ์ง์ ๋ถ๊ฐ)
- ์ซ์ ๋น๊ต(>, <) ์ ๊ฐ์ ์ฐ์ฐ ๋ถ๊ฐ
- ์กฐ์ธ ํ ์ด๋ธ์ ํ๋ ๊ฒ์ ์ด๋ ค์
- ์์ฑ์ null์ด ์์ผ๋ฉด ์๋ ๋ฌด์๋๋ฏ๋ก null์ ํฌํจํ๋ ๊ฒ์์ด ์ด๋ ค์
๐ ๋ณต์กํ ๊ฒ์์ด ํ์ํ๋ฉด Specification์ด๋ QueryDSL์ ์ฌ์ฉํ๋ ๊ฒ์ด ํจ์จ์ ์ด๋ค.
์ฐธ๊ณ ์๋ฃ
https://docs.spring.io/spring-data/relational/reference/query-by-example.html
'Spring > Spring & Spring Boot' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Spring] Spring Batch 5 ์ฌ์ฉํด๋ณด๊ธฐ (0) | 2024.07.31 |
---|---|
[Spring] Spring Batch๋ก ํ ๋ฌ ์ง๋ ๋ฐ์ดํฐ ์ญ์ ํ๊ธฐ (0) | 2024.07.29 |
[Spring/Spring Boot] SSE (Server-Sent Events)์ EventSource ์ ์ฉํด๋ณด๊ธฐ (0) | 2024.05.14 |
[Spring] Spring Security @AuthenticationPrincipal (0) | 2024.04.10 |
[Spring] ํํฐ(Filter)์ ์ธํฐ์ ํฐ(Interceptor) (0) | 2024.03.18 |