• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

Optional 관련 질문있습니다.

20.05.18 23:25 작성 조회수 149

0

스프링 데이터 Common 3. Null 처리를 보고 궁금한게 있습니다!

아래 CommentRepotoryTest 클래스에 crud 메서드에서 MyRepository에 정의하고 CommentRepository가 상속받은 findById(ID id)를 테스트 하고 있었습니다.

현재 DB에 ID가 3에 해당하는 글이 존재하기 때문에 comment 변수에 해당 정보가 들어가 있겠거니 생각했는데 생각과는 달리 Optional을 Comment 객체로 캐스팅 할 수 없다는 오류가 발생하였습니다.

MyRepository와 CommentRepository에서는 Optional 관련 코드가 전혀 없는데 해당 오류가 어떤 이유로 인해 발생하는지 전혀 모르겠습니다.

@NoRepositoryBean
public interface MyRepository<T, ID extends Serializable> extends Repository<T,ID> {

    <E extends T> E save(E Entity);

    List<T> findAll();

    int count();

    <E extends T> E findById(ID id);

    /*@Nullable
    <E extends T> E findById(ID id);*/
}

public interface CommentRepository extends MyRepository<Comment,Long> {
}

@RunWith(SpringRunner.class)
@DataJpaTest
public class CommentRepostoryTest {

    @Autowired
    CommentRepository commentRepository;

    @Test
    public void crud(){
        Comment comment = commentRepository.findById(3l);
    }
}

답변 1

답변을 작성해보세요.

0

커스텀 리파지토리 인터페이스를 정의하셨지만, 그 구현은 스프링 데이터 JPA가 제공하는데, 스프링 데이터 JPA 구현체에는 Optional을 사용한 findById 밖에 없기 때문입니다. 즉, 원하시는 findById는 직접 커스텀한 구현체까지 만들어서 제공해야 합니다.