Contents
Service public List<Board> findAll() {
return em.createQuery("select b from Board b order by b.id").getResultList();
}
public Optional<Board> findById(int id) {
return Optional.ofNullable(em.find(Board.class, id));
}
public void save(Board board) { // board 객체를 만들어서 던지면 insert해준다.
em.persist(board);
}
public void delete(int id) {
em.createQuery("delete from Board b where b.id = :id").setParameter("id", id).executeUpdate();
}

db에서 조회할 때 터진 것이 아니라 null에서 값을 꺼내려고 null.getId이 불러와지면서 터짐
→ 서비스레이어에서 호출할 때 터진 것이다.
→null처리를 해줘야한다.
→ Repository에서 Optional이라는 컨테이너로 감싼 걸 넘긴다. 안에는 null일수도 board일수도 있다. 컨테이너는 null이 아님 → nullpointexception 방지
public Optional<Board> findById(int id) {
return Optional.ofNullable(em.find(Board.class, id));
}
Service
public BoardResponse.DetailDTO 게시글상세보기(int id) {
Board board = boardRepository.findById(id)
.orElseThrow(()->new RuntimeException("해당 id의 게시글이 없습니다:"+id));
return new BoardResponse.DetailDTO(board);
}

Share article