Обработка запроса с сервера h2 spring boot

Рейтинг: -1Ответов: 1Опубликовано: 07.05.2023

Есть база данных h2. В ней хранятся какие-то данные. Я могу получить строчку по такому запросу:

@GetMapping("/cproducts/{id}")
    public ResponseEntity<Product> getProductById(@PathVariable("id") long id) {
        Optional<Product> tutorialData = productRepository.findById(id);

        if (productData.isPresent()) {
            return new ResponseEntity<>(productData.get(), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

Как получить столбец (определенное значение колонки) из полученного запроса выше? (т е из запроса выше мы получаем что-то по типу такого: {"id":1, "title":"first"}, а как получить из этого запроса только title?)

Заранее спасибо!

Ответы

▲ 1Принят

Если достаточно вернуть простое строковое значение заданного поля, это можно сделать так (в отдельном методе контроллера):

@GetMapping("/cproducts/{id}/title")
public ResponseEntity<?> getProductTitleById(@PathVariable("id") long id) {
    return productRepository.findById(id)
        .map(p -> ResponseEntity.ok(product.getTitle()))
        .orElseGet(() -> ResponseEntity.notFound().build());
}

Если нужно вернуть ответ в виде JSON-обёртки: {"title": "my product title"}, следует использовать DTO-класс (data transfer object) и преобразовать найденный товар в экземпляр DTO:

@Data
@RequiredArgsConstructor
public class TitleDTO {
    private final String title;
}
@GetMapping("/cproducts/{id}/title")
public ResponseEntity<?> getProductTitleById(@PathVariable("id") long id) {
    return productRepository.findById(id)
        .map(p -> ResponseEntity.ok(new TitleDTO(p.getTitle()))
        .orElseGet(() -> ResponseEntity.notFound().build());
}

В Spring 6 был добавлен метод ResponseEntity::ofNullable, тогда код упростится:

@GetMapping("/cproducts/{id}/title")
public ResponseEntity<String> getProductTitleById(@PathVariable("id") long id) {
    return ResponseEntity.ofNullable(productRepository.findById(id)
        .map(Product::getTitle)
        .orElse(null)
    );
}
@GetMapping("/cproducts/{id}/title")
public ResponseEntity<TitleDTO> getProductTitleById(@PathVariable("id") long id) {
    return ResponseEntity.ofNullable(productRepository.findById(id)
        .map(p -> new TitleDTO(p.getTitle()))
        .orElse(null)
    );
}