Optional<T>
- Integer나 Double 클래스처럼 'T'타입의 객체를 포장해 주는 래퍼 클래스(Wrapper class)
- 모든 타입의 참조 변수를 저장할 수 있다.
- 예상치 못한 NullPointerException 발생 시 제공되는 메소드로 예외를 처리할 수 있다.
Optional 객체 생성
- of() 메소드나 ofNullable() 메소드를 사용하여 Optional 객체를 생성
Optional<String> opt = Optional.ofNullable("optional 객체");
- of()는 명시된 값을 가지는 Optional 객체를 반환한다.
- of()를 통해 생성된 객체에 null이 저장되면 NullPointerException 예외가 발생
- 참조 변수의 값이 null이 될 가능성이 있다면 ofNullable() 메소드를 사용하여 객체를 생성하는 것이 좋다.
- ofNullable()를 통해 생성된 객체에 null 값 이 저장되면 반환 시 빈 Optional 객체가 반환된다.
Optional 객체 메서드
get()
- get()를 사용하면 Optional 객체에 저장된 값에 접근할 수 있다.
- Optional 객체가 null 일 때 get()을 사용하면 NoSuchElementException 예외가 발생하므로 접근 전 isPresent()를 사용하여 객체 값 여부를 확인 후 접근하는 것이 좋다.
Optional<String> optinal = Optional.ofNullable("Optional 객체");
if(optinal.isPresent()) {
System.out.print(optinal.get());
}
isPresent()
- Boolean 타입
- Optional 객체가 값을 가지고 있다면 true, 값이 없다면 false 리턴
@Test
public void delete() {
Optional<AdminUser> findUser = adminUserRepository.findAdminUserByUserid("apple");
findUser.ifPresent(
selectUser -> {
adminUserRepository.delete(selectUser);
}
);
Optional<AdminUser> deleteUser = adminUserRepository.findAdminUserByUserid("apple");
if(deleteUser.isPresent()) {
System.out.println("삭제 실패!");
} else {
System.out.println("삭제 성공!");
}
}
apple 유저 삭제 실행 후 삭제가 잘 되었는지 확인하기 위해 isPresent() 사용
ifPresent()
- Optional 객체가 값을 가지고 있는지 확인 후 예외처리
@Test
public void update() {
Optional<AdminUser> findUser = adminUserRepository.findAdminUserByUserid("apple");
findUser.ifPresent(
selectUser -> {
selectUser.setStatus("탈퇴");
adminUserRepository.save(selectUser);
}
);
}
apple 유저를 Optional 객체에 저장한 후 객체가 null 값이 아니면 유저의 상태 변경
'SpringBoot(JPA,Gradle)' 카테고리의 다른 글
[SpringBoot] Enum Class (1) | 2023.05.25 |
---|---|
[SpringBoot] mySQL 연동 (1) | 2023.05.25 |
[SpringBoot] 로그 (0) | 2023.03.27 |
[SpringBoot] CRUD 단위 테스트 (0) | 2022.06.22 |
[SpringBoot] Repository 생성 (0) | 2022.06.22 |