Reputation: 15
I am relatively new in the world of Spring Boot and I have a problem with storing the data in database in my project. I have these entities: Flight - (flight number, gate, airport departure, airport arrival etc.), Passenger (passport number, name, surname etc.), Ticket( ticket number, passport_number(foreign key referencing Passenger table), flight_number(foreign key referencing Flight table)) and Luggage(id, ticket number(foreign key referencing Ticket table). When I want to make a reservation, first I want to save the data about the passenger, then save the data about the ticket(using the passport_number of the new passenger) and at the end to save the data about the luggage(also using the passport_number of the new passenger) and I want the whole process to be like a transaction. But I constantly get an error java.util.NoSuchElementException: No value present at java.base/java.util.Optional.get(Optional.java:141) ~[na:na] when I am saving the passenger. Here is the code. Any suggestions how can I solve this problem? Here is the code from the controller where I am trying to save the data. Thank you so much.
@PostMapping("/confirmTicket")
@Transactional
public String confirmTicket(HttpServletRequest req) {
Passenger passenger = (Passenger) req.getSession().getAttribute("passenger");
Flight flight = (Flight) req.getSession().getAttribute("flight");
Passenger passengerNew = passengerService.save(passenger.getPassport_number(), passenger.getFirst_name(), passenger.getLast_name(),
passenger.getEmail(), passenger.getAddress(), passenger.getPhone_number(), passenger.getAccount_number()).get();
Ticket ticket = ticketService.save(Integer.parseInt(req.getSession().getAttribute("seat").toString()), flight.getPrice(),
Class.valueOf(req.getSession().getAttribute("class").toString()), "", passengerNew, flight).get();
luggageService.save(LuggageType.valueOf(req.getSession().getAttribute("luggage").toString()),
Integer.parseInt(req.getSession().getAttribute("weight").toString()), ticket);
return "redirect:/home";
}
Upvotes: 0
Views: 14618
Reputation: 92
xyz.get() method returns this error if xyz is null . passengerService.save(....) is returning empty value ,check this service methos properly
Upvotes: 2
Reputation: 742
You're calling get
on an Optional without first checking if the Optional is present. Calling get
on an empty Optional results in a NoSuchElementException
Either call isPresent
first or use orElse
instead.
Optional<String> emptyOptional = Optional.ofNullable(null);
Optional<String> optional = Optional.of("Not empty");
emptyOptional.get(); // NoSuchElementException
optional.get(); // "Not empty"
emptyOptional.orElse(null); // null
optional.orElse(null); // "Not empty"
emptyOptional.orElse("default value"); // "default value"
optional.orElse("default value"); // "Not empty"
emptyOptional.isPresent(); // false
optional.isPresent(); // true
Upvotes: 2