java.util.NoSuchElementException: No value present

Olá Boa noite, estou começando com SpringBoot por agora e fui fazer uma alteração no Css e acabei com esse erro, java.util.NoSuchElementException: No value present, alguém sabe como consertar esse erro? Seguem abaixo os códigos:

Reserva.java

package br.edu.usj.ads.pw.agenda;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Entity
@Getter
@Setter
@NoArgsConstructor
public class Reserva {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    String nome;
    String tipo;
    String telefone;

}

Classe Controller.java

package br.edu.usj.ads.pw.agenda;

import java.util.ArrayList;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.servlet.ModelAndView;

@Controller

public class ReservaController {

    @Autowired

    ReservaRepository reservaRepository;

    @GetMapping(value="/")

    public ModelAndView getIndex() {

        // criar um objeto lista

        List<Reserva> lista = new ArrayList<>();

        // preencher esta lista com os dados do banco

        lista = reservaRepository.findAll();

        // instanciar um template

        ModelAndView modelAndView = new ModelAndView("index");

        // preencher o template com a lista

        modelAndView.addObject("lista", lista);

        //retornar o template

        return modelAndView;

    }

    @GetMapping(value="/editar/{id}")

    public ModelAndView getEditar(@PathVariable Long id) {

        Reserva reserva = new Reserva();

        reserva = reservaRepository.findById(id).get();

        ModelAndView modelAndView = new ModelAndView("cadastro");

        modelAndView.addObject("reserva", reserva);

        return modelAndView;

    }

    @GetMapping(value="/detalhes/{id}")

    public ModelAndView getDetalhes(@PathVariable Long id) {

        // ler reserva no banco pelo id

        Reserva reserva = new Reserva();

        reserva = reservaRepository.findById(id).get();

        // instanciar o template

        ModelAndView modelAndView = new ModelAndView("detalhes");

        // preencher o template com o reserva selecionado

        modelAndView.addObject("reserva", reserva);

        // retornar template

        return modelAndView;

    }

    @GetMapping(value="/cadastro")

    public ModelAndView getCadastro() {

        Reserva reserva = new Reserva();

        ModelAndView modelAndView = new ModelAndView("cadastro");

        modelAndView.addObject("reserva", reserva);

        return modelAndView;

    } 

    @PostMapping(value="/adicionar")

    public ModelAndView postAdicionar(Reserva reserva) {

        // salvar no banco (usando repository)

        reservaRepository.save(reserva);

        // criar template

        ModelAndView modelAndView = new ModelAndView("detalhes");

        // popular o template

        modelAndView.addObject("reserva", reserva);

        // retornar

        return modelAndView;

    }

    @GetMapping(value="/deletar/{id}")

    public String getDeletar(@PathVariable Long id) {

        // deletar o objeto com o id passado pelo parametro

        reservaRepository.deleteById(id);

        // retornar o template 

        return "redirect:/";

    }
}

data.sql

insert into reserva (id, nome, tipo, telefone) values (1, 'Fulano', 'Casamento', '1234-1234')

insert into reserva (id, nome, tipo, telefone) values (2, 'Beltrano', 'Formatura', '9876-5432')

insert into reserva (id, nome, tipo, telefone) values (3, 'Sicrano', 'Aniversário', '3334-2234')

detalhes.html

<!DOCTYPE html>
<html lang="pt-BR">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Detalhes - Reserva</title>

    <link rel="stylesheet" href="/css/style.css" />

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script>

    <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://icon-library.com/images/agenda-icon/agenda-icon-8.jpg">

</head>

<body style="background-color: rgb(248, 209, 100)">
    <h1 class="center">

        <img src="https://i.pinimg.com/originals/77/f0/7c/77f07c8002d89e9d6f56f9d6df7a9199.png" class="mr-0" alt="Agenda" width="64"height="64">

        Detalhes - Reserva

        <img src="https://i.pinimg.com/originals/77/f0/7c/77f07c8002d89e9d6f56f9d6df7a9199.png" class="mr-0" alt="Agenda" width="64"height="64">

    </h1><br>

    <h2 style="text-align: center; color:#000">Informações de Reserva</h2><br>

        <!--Início Carousel-->

    <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">

        <ol class="carousel-indicators">

          <li data-interval="500" data-slide-to="0" class="active"></li>

          <li data-interval="500" data-slide-to="1"></li>

          <li data-interval="500" data-slide-to="2"></li>

        </ol>

        <div class="carousel-inner">

          <div class="carousel-item active">

            <img class="d-block w-100" src="https://blog.saipos.com/wp-content/uploads/2018/10/Dicas-de-pratos-para-restaurante-SAIPOS-Sistema-para-Restaurantes-1.jpg" width="450" height="490" alt="Comida 01">

          </div>

          <div class="carousel-item">

            <img class="d-block w-100" src="https://ibis.accor.com/editorial/imagerie/article/comida-mineira-pratos-tipicos-de-cada-regiao-do-brasil-358a_660x440.jpg" width="450" height="490" alt="Comida 02">

          </div>

          <div class="carousel-item">

            <img class="d-block w-100" src="https://img.elo7.com.br/product/zoom/22565B3/adesivo-parede-prato-comida-frango-salada-restaurante-lindo-adesivo-parede.jpg" width="450" height="490" alt="Comida 03">

          </div>

        </div>

        <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">

          <span class="carousel-control-prev-icon" aria-hidden="true"></span>

          <span class="sr-only">Previous</span>

        </a>

        <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">

          <span class="carousel-control-next-icon" aria-hidden="true"></span>

          <span class="sr-only">Next</span>

        </a>

      </div>

    <!--Fim Carousel-->

        <br>

    <div class="center">

        <h1 th:text="${reserva.nome}"></h1>

        <h2 th:text="${reserva.tipo}"></h2>

        <h3 th:text="${reserva.telefone}"></h3>

    </div><br>

    <div style="text-align: center; padding-bottom: 20px;">

        <a class="button" href="/" role="button">Voltar ao Início</a>

    </div>

</body>

</html>

Tem algum lugar no código que vc está usando Optional?

Não, estou com problema em adicionar um novo tipo, conta como se não existisse

Suspeito que o problema esteja nessa linha:

reserva = reservaRepository.findById(id).get();

Se for informado um id que não exista, ao chamar o get(), vai estourar exatamente esse erro: java.util.NoSuchElementException: No value present.

O correto seria vc não usar o get() diretamente, mas fazer uma verificação antes:

Optional<Reserva> reservaOptional = reservaRepository.findById(id);

if (reservaOptional.isPresent()) {
    reserva = reservaOptional.get();
} else {
   // caso o optional esteja vazio, faça algum tratamento
}

Estou informando o id no Reserva,java, o modelo seria para criar um id novo a cada adição no Bd, mas não está conseguindo fazer esta parte de adicionar.
E mesmo com o Optional ele não consegue acessar o id do Reserva.java.

Problema dos campos nulos. Resolvido:

Obs(Problema Estava na Página de Cadastro)

O input por algum motivo deve ter o mesmo nome que os atributos da classe. No meu caso, um dos atributos tinha esse nome “tipo” e então o input recebe id e name iguais.

1 curtida