Projection
public interface UserProfile {
String getUsername();
String getProfileImageUrl();
}
// select username, profileImageUrl from user; // closed projection
@Value(SpEL)
을 사용해서 연산을 할 수 있다.// workersHolder 는 bean 으로 등록한 contextHolder
@Value("#{workersHolder.salaryByWorkers['George']}")
private Integer georgeSalary;
public interface UserProfile {
@Value('#{target.profileImageUrl != null}')
Boolean hasProfileImage;
}
public interface UserProfile {
String getUsername();
String getProfileImageUrl();
@Value("#{target.profileImageUrl != null}")
boolean hasProfileImage();
default String getUserInfo() {
return getUsername() + " " + (hasProfileImage() ? getProfileImageUrl() : "");
}
}
// UserRepository.java
List<UserProfile> findByUsername(String username);
@Test
void projectionTest() {
// given
var newUser = User.builder().username("user").profileImageUrl("http://").password("pass")
.build();
// when
var savedUser = userRepository.save(newUser);
// then interface projection
var userProfiles = userRepository.findByUsername("user");
System.out.println("interface projection : ");
userProfiles.forEach(userProfile -> System.out.println(userProfile.hasProfileImage()));
assert !userProfiles.isEmpty();
}
@Getter
@AllArgsConstructor
public class UserInfo {
private String username;
private String password;
public String getUserInfo() {
return username + " " + password;
}
}
// UserRepository.java
List<UserInfo> findByPassword(String password);
@Test
void projectionTest() {
// given
var newUser = User.builder().username("user").profileImageUrl("http://").password("pass")
.build();
// when
var savedUser = userRepository.save(newUser);
// then class projection
var userInfos = userRepository.findByPassword("pass");
System.out.println("class projection : ");
userInfos.forEach(userInfo -> System.out.println(userInfo.getUserInfo()));
assert !userInfos.isEmpty()
}
// UserRepository.java
<T> List<T> findByProfileImageUrlStartingWith(String profileImageUrlStartWith, Class<T> type);
@Test
void projectionTest() {
// given
var newUser = User.builder().username("user").profileImageUrl("http://").password("pass")
.build();
// when
var savedUser = userRepository.save(newUser);
// then dynamic projection
var userProfiles2 = userRepository.findByProfileImageUrlStartingWith("http", UserProfile.class);
System.out.println("dynamic projection1 : ");
userProfiles2.forEach(userProfile -> System.out.println(userProfile.getProfileImageUrl()));
assert !userProfiles2.isEmpty();
// then dynamic projection
var userInfos2 = userRepository.findByProfileImageUrlStartingWith("http", UserInfo.class);
System.out.println("dynamic projection2 : ");
userInfos2.forEach(userInfo -> System.out.println(userInfo.getProfileImageUrl()));
assert !userProfiles2.isEmpty();
}