Optional 의 반환값

CosmoNumb·2024년 7월 23일
0

java

목록 보기
16/24

JpaRepository 인터페이스의 findById(id) 메서드는 항상 Optional<T> 형식으로 반환합니다. 이는 특정 ID에 해당하는 엔티티가 데이터베이스에 존재할 수도 있고, 존재하지 않을 수도 있는 상황을 처리하기 위해 설계되었습니다.

Optional<T> 형식 반환의 이유

  1. Null 안전성:
    • Optional을 사용하면 null 값의 존재를 명시적으로 처리할 수 있습니다. 이는 null 포인터 예외(NullPointerException)를 방지하고 코드를 더 안전하게 만듭니다.
  2. 명확한 의도 표현:
    • Optional을 반환함으로써 호출자에게 값이 없을 수도 있다는 가능성을 명확히 알립니다. 이는 메서드의 의도를 명확하게 표현하는 데 도움이 됩니다.

예시 코드

다음은 JpaRepository 인터페이스의 findById(id) 메서드를 사용하는 예입니다:

StudentRepository 인터페이스

package repository;

import model.Student;
import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository<Student, Long> {
    // JpaRepository는 기본 CRUD 메서드를 제공합니다.
}

StudentService 클래스

package service;

import model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import repository.StudentRepository;
import java.util.List;
import java.util.Optional;

@Service
public class StudentService {

    @Autowired
    private StudentRepository studentRepository;

    // 모든 학생 조회
    public List<Student> getAllStudents() {
        return studentRepository.findAll();
    }

    // ID로 학생 조회
    public Student getStudentById(Long id) {
        Optional<Student> optionalStudent = studentRepository.findById(id);
        return optionalStudent.orElse(null);  // 값이 없으면 null 반환
    }

    // 학생 저장
    public Student saveStudent(Student student) {
        return studentRepository.save(student);
    }

    // ID로 학생 삭제
    public void deleteStudent(Long id) {
        studentRepository.deleteById(id);
    }
}

Optional의 주요 메서드

  1. isPresent():

    • Optional에 값이 존재하는지 확인합니다.
    Optional<Student> optionalStudent = studentRepository.findById(id);
    if (optionalStudent.isPresent()) {
        return optionalStudent.get();
    } else {
        return null;
    }
  2. ifPresent(Consumer<? super T> action):

    • 값이 존재할 때 특정 동작을 수행합니다.
    optionalStudent.ifPresent(student -> System.out.println(student.getName()));
  3. orElse(T other):

    • 값이 존재하면 그 값을 반환하고, 그렇지 않으면 다른 값을 반환합니다.
    Student student = optionalStudent.orElse(new Student("Default Name", 0));
  4. orElseGet(Supplier<? extends T> other):

    • 값이 존재하면 그 값을 반환하고, 그렇지 않으면 다른 값을 계산하여 반환합니다.
    Student student = optionalStudent.orElseGet(() -> new Student("Default Name", 0));
  5. orElseThrow(Supplier<? extends X> exceptionSupplier):

    • 값이 존재하면 그 값을 반환하고, 그렇지 않으면 예외를 던집니다.
    Student student = optionalStudent.orElseThrow(() -> new EntityNotFoundException("Student not found"));

결론

JpaRepositoryfindById(id) 메서드는 항상 Optional<T> 형식으로 반환합니다. 이를 통해 데이터베이스에서 값을 안전하게 조회하고, 값이 존재하지 않을 경우를 명시적으로 처리할 수 있습니다. Optional 클래스는 값이 존재하지 않을 가능성을 처리하기 위한 다양한 메서드를 제공하여, 코드의 안정성과 가독성을 높이는 데 기여합니다.

0개의 댓글