์ํฐํฐ ๋์ ์ DTO๋ฅผ ํธ๋ฆฌํ๊ฒ ์กฐํํ ๋ ์ฌ์ฉ
์ ์ฒด ์ํฐํฐ๊ฐ ์๋๋ผ ๋ง์ฝ ํ์ ์ด๋ฆ๋ง ๋ฑ ์กฐํํ๊ณ ์ถ์ผ๋ฉด?
์ธํฐํ์ด์ค๋ฅผ ๋ง๋ค์ด์ค๋ค.
public interface UsernameOnly {
String getUsername();
}
public interface MemberRepository ... {
List<UsernameOnly> findProjectionsByUsername(String username);
}
ํ ์คํธ๋ ์๋์ ๊ฐ๋ค.
์ธํฐํ์ด์ค ๊ธฐ๋ฐ Open Proejctions
๋ค์๊ณผ ๊ฐ์ด ์คํ๋ง์ SpEL ๋ฌธ๋ฒ๋ ์ง์ํ๋ค.
public interface UsernameOnly {
@Value("#{target.username + ' ' + target.age + ' ' + target.team.name}")
String getUsername();
}
๋จ! ์ด๋ ๊ฒ SpEL๋ฌธ๋ฒ์ ์ฌ์ฉํ๋ฉด, DB์์ ์ํฐํฐ ํ๋๋ฅผ ๋ค ์กฐํํด์จ ๋ค์์ ๊ณ์ฐํ๋ค! ๋ฐ๋ผ์ JPQL SELECT ์ ์ต์ ํ๊ฐ ์๋๋ค.
ํด๋์ค ๊ธฐ๋ฐ Projection
๋ค์๊ณผ ๊ฐ์ด ์ธํฐํ์ด์ค๊ฐ ์๋ ๊ตฌ์ฒด์ ์ธ DTO ํ์๋ ๊ฐ๋ฅ
์์ฑ์์ ํ๋ผ๋ฏธํฐ ์ด๋ฆ์ผ๋ก ๋งค์นญ
package study.datajpa.repository;
public class UsernameOnlyDto {
private final String username;
public UsernameOnlyDto(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
}
๋์ Projections
๋ค์๊ณผ ๊ฐ์ด Generic type์ ์ฃผ๋ฉด, ๋์ ์ผ๋ก ํ๋ก์ ์
๋ฐ์ดํฐ ๋ฒ๊ฒฝ ๊ฐ๋ฅ
<T> List<T> findProjectionsByUsername(String username, Class<T> type);
์ค์ฒฉ ๊ตฌ์กฐ ์ฒ๋ฆฌ
public interface NestedClosedProjection {
String getUsername();
TeamInfo getTeam();
interface TeamInfo {
String getName();
}
}
์ฃผ์
- ํ๋ก์ ์ ๋์์ด root ์ํฐํฐ๋ฉด, JPQL SELECT ์ ์ต์ ํ ๊ฐ๋ฅ
- ํ๋ก์ ์
๋์์ด ROOT๊ฐ ์๋๋ฉด
- LEFT OUTER JOIN ์ฒ๋ฆฌ
- ๋ชจ๋ ํ๋๋ฅผ SELECTํด์ ์ํฐํฐ๋ก ์กฐํํ ๋ค์์ ๊ณ์ฐ
์ ๋ฆฌ
- ํ๋ก์ ์ ๋์์ด root ์ํฐํฐ๋ฉด ์ ์ฉํ๋ค.
- ํ๋ก์ ์ ๋์์ด root ์ํฐํฐ๋ฅผ ๋์ด๊ฐ๋ฉด JPQL SELECT ์ต์ ํ๊ฐ ์๋๋ค!
- ์ค๋ฌด์ ๋ณต์กํ ์ฟผ๋ฆฌ๋ฅผ ํด๊ฒฐํ๊ธฐ์๋ ํ๊ณ๊ฐ ์๋ค.
- ์ค๋ฌด์์๋ ๋จ์ํ ๋๋ง ์ฌ์ฉํ๊ณ , ์กฐ๊ธ๋ง ๋ณต์กํด์ง๋ฉด QueryDSL์ ์ฌ์ฉํ์
'Spring-study๐ฑ > SpringData-JPA' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Section 7-4. ๋ค์ดํฐ๋ธ ์ฟผ๋ฆฌ (0) | 2023.01.30 |
---|---|
Section 7-2. Query By Example (0) | 2023.01.29 |
Section 7-1. Specifications (๋ช ์ธ) (0) | 2023.01.29 |
Section 6-2. ์๋ก์ด ์ํฐํฐ๋ฅผ ๊ตฌ๋ณํ๋ ๋ฐฉ๋ฒ (0) | 2023.01.29 |
Section 6-1. ์คํ๋ง ๋ฐ์ดํฐ JPA ๊ตฌํ์ฒด ๋ถ์ (0) | 2023.01.29 |