API

화면 HTML 없이 값만 JSON으로 돌려줍니다.

RestController

@RestController 메서드의 반환값은 템플릿 이름이 아니다. Spring이 객체를 JSON으로 바꿔 응답한다. 지도 화면이 목록만 다시 받을 때 이 주소를 쓴다.

@RestController
@RequestMapping("/api/villa")
public class ApiVillaController {
    private final VillaService villaService;

    public ApiVillaController(VillaService villaService) {
        this.villaService = villaService;
    }

    @GetMapping("/{id}")
    public VillaDetail detail(@PathVariable Long id) {
        return villaService.detail(id);
    }
}

GET /api/villa/15이면 id는 15다. 본문을 보내는 저장은 @PostMapping과 인자 객체로 받는다.

리포지토리

서비스가 호출하는 저장 인터페이스는 JPA가 구현한다. 메서드 이름이 조회 조건이 된다.

public interface VillaRepository extends JpaRepository<Villa, Long> {
    List<Villa> findByTitleContaining(String keyword);
}

실제로 나가는 문장은 SQL이다. MariaDB에서 그 문장을 직접 쓰는 법은 MariaDB · 조회·변경에 있다. 표 설계와 where의 의미는 PostgreSQL · 조회·변경과 같다.

없는 id로 조회하면 빈 결과를 구분한다. 컨트롤러가 무조건 200과 빈 객체를 돌려주면 화면은 성공으로 오해한다. 없을 때는 404에 해당하는 응답을 고른다.