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";
}
xyz.get() method returns this error if xyz is null .
passengerService.save(....) is returning empty value ,check this service methos properly
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
Related
I am creating a customer manager application for a Java course. I have it separated as per the requirements into 3 packages. The first package has a class called Customer, which models a customer and it's instance variables, such as customerID. The second package is a customer database that includes an ArrayList. The third package is going to be a menu driven UI that will allow the user to choose between 4 options. Currently, I am stuck trying to write a method that will search through the list for a given customerID and return a Customer object.
In the customer database class, I am getting the customerID from the user within the method. Then, I am running a for loop that should traverse the method to see if the customerID is found. I am having issues on how to return a customer object if the id is a match.
public Customer searchCustomer(String customerID) {
System.out.println("Enter customer ID you want to find:");
customerID = scnr.next();
Customer c;
for (int i = 0, i < customerList.size(); i++ {
c = customerList.get(i);
if (customerList.get(i).equals(customerID) {
String foundID = customerID;
}
}
}
I want to return Customer c at the end of the method, but cannot figure out how to do this.
In the if statement one can just write return c. This will return the first Customer that matches. At the end of the method one can return null or throw an exception if the Customer wasn’t found.
You compare Customer object with CustomerId.
Change code to
if (customerList.get(i).getId().equals(customerID) {
return customerList.get(i);
}
A few of the potential mistakes you're making are:
Passing in an parameter to your method that you're not using. Either do the Scanner stuff outside of the method and then pass the ID to the method, or do the Scanner part in the method and have no parameters. The former approach is generally the preferred one, though.
Comparing the customer to a String. You need to compare the user-entered ID to the Customer object's ID field. The String the user enters will never be equal to the entire Customer object.
You're not returning anything from the method. Once you find the Customer you're looking for, you need a return statement.
Also, you can use Java's "enhanced for loop" to make the code a bit cleaner. Here's some code that assumes that your Customer objects use a String as their ID, and have a .getID() method on them to get their ID.
Here's some code that needs to search for a customer. This can be in another method.
System.out.println("Enter customer ID you want to find: ");
customerID = scnr.next();
Customer customer = searchCustomer(customerID);
And here's the search method that loops through the customerList
public Customer searchCustomer(String customerID) {
for(Customer customer : customerList) {
if (customer.getId().equals(customerID) ) {
return customer;
}
}
return null; // Or perhaps throw an exception.
}
Note that I'm making a lot of assumptions about how the other parts of your code that I haven't seen are structured, so you very probably will have to modify this code sample if you want to use it, but hopefully it puts you on the right track.
The following code is part of a large project.
Overview is that I am trying to access a database using Spring MVC. I want to update a field based on request and send a response as to what values the database sent back.
Code:
#Override
#Transactional
public EmployeeResponse update(EmployeeRequest employeeRequest) {
Employee emp = new Employee();
UUID empId = UUID.fromString(employeeRequest.getId());
Employee foundEmployee = employeeRepository.findOne(empId);
if (foundEmployee != null) {
foundEmployee.setAddress(employeeRequest.getAddress());
// similarly set 4 fields of foundEmployee
emp = employeeRepository.save(foundEmployee);
}
EmployeeResponse response = new EmployeeResponse();
response.setAddress(emp.getAddress());
// similarly set 4 fields of response
return response;
}
I found that there was no new Employee() for foundEmployee as there is for emp.
I am not sure but I think this'll cause exceptions.
Am I correct?
Also, please tell me what exception I should throw when foundEmployee is null.
Additional info - this is what the help shows:
org.springframework.data.repository.CrudRepository
public T findOne(ID id)
Retrieves an entity by its id.
Parameters:
id - must not be null.
Returns:
the entity with the given id or null if none found
Throws:
IllegalArgumentException - if id is null
In the line
Employee foundEmployee = employeeRepository.findOne(empId);
we can presume that EmployeeRepository.findOne() will return an instance of Employee. This will not cause a compiler error, and if an exception happens at runtime, it would be inside findOne().
With regard to what you should do in the event of a null foundEmployee, it is really a design decision you will have to make. One option would be to have the method return null to let the consumer know that the EmployeeRequest which was passed in had a serious problem with it.
Another option would be to create your own Exception and then throw it in the case of null foundEmployee.
Update:
In light of that you need to pass something back to your UI, another option would be to create an empty EmployeeReponse object and return that:
EmployeeResponse response = new EmployeeResponse();
response.setAddress(null);
response.setName(null);
Make sure that your framework can marshall null values into something which is user friendly, for example an empty string for all fields.
for(int i=0;i<ab.list.size();i++)
{
System.out.print( "Account: "+ab.ba.getCustomer().getAcct()+"\nDate:\n"+c);
}
ab is a Database object.
ba is a bank account object
from which you get getCustomer() and getAcct() methods to return a customer object and the method within it, getAcct(), the account number I'm trying to print for each location.
Now, it says this when I try and print it
java.lang.NullPointerException
Is that because list only returns pointers?
It seems that you are working in JPA and forgettten to add the MappedBy attribute in the one to many annotation
Or the entity is new
HTH
I am trying to add a filter to check for duplicate values that a user might input. I am not sure where I am going going wrong in my query.
My query doesnot enter the loop to check if the name already exists.
I am fairly new to google-could. If someone can tell me on how I can fix my problem or if there is a better solution.
else if ( commandEls[0].equals( "add_director" ) ) {
String name = commandEls[1];
String gender = commandEls[2];
String date_of_birth = commandEls[3];
boolean duplicate = false;
//add a director record with the given fields to the datastore, don't forget to check for duplicates
Entity addDirectorEntity = new Entity("Director");
// check if the entity already exits
// if !duplicate add, else "Already exisits"
Query directorExists = new Query("Movies");
// Director Name is the primary key
directorExists.addFilter("directorName",Query.FilterOperator.EQUAL, name);
System.out.print(name);
PreparedQuery preparedDirectorQuery = datastore.prepare(directorExists);
System.out.print("outside");
for(Entity directorResult : preparedDirectorQuery.asIterable()){
// result already exists in the database
String dName = (String) directorResult.getProperty(name);
System.out.print(dName);
System.out.print("finish");
duplicate = true;
}
if(!duplicate){
addDirectorEntity.setProperty("directorName",name);
addDirectorEntity.setProperty("directorGender",gender);
addDirectorEntity.setProperty("directorDOB",date_of_birth);
try{
datastore.put(addDirectorEntity);
results = "Command executed successfully!";
}
catch(Exception e){
results = "Error";
}
}
else {
results = "Director already exists!";
}
}
Non-ancestor queries (like the one in your example) are eventually consistent, so they cannot reliably detect duplicate property values. Ancestor queries are fully consistent, but they require structuring your data using entity groups, and that comes at the cost of write throughput.
If the directorName property in your example is truly unique, you could use it as the name in the key of your Director entities. Then, when you are inserting a new Director entity, you can first check if it already exists (inside of a transaction).
There's no general, built-in way in Datastore to ensure the uniqueness of a property value. This related feature request contains discussion of some possible strategies for approximating a uniqueness constraint.
I'd also recommend reading up on queries and consistency in the Datastore.
That is a valid thing to do but i figured out my problem.
I am making an Entity for Director where as That should be for movies.
I am currently using a hashmap to store information about a Current Account.
Here is what I have in one method:
HashMap<String, Account> account = new HashMap<String, Account>();
if (Account.validateID(accountID)) {
System.out.println("Account ID added");
Account a = new Account(cl,accountID, sortCode, 0);
account.put(accountID, a); //add to HashMap
}
This seems to work fine. Then in another method I have:
public void enterTransaction()
{
String tAccountID = JOptionPane.showInputDialog(this,
"Enter valid accountID", "Add Account", 0);
System.out.println("Check if accountID exists: " + account.containsKey(tAccountID)); //testing if accountID exists - currently not working
Date currentDate = new Date();
System.out.println("Date and time of transaction: " + currentDate); //prints the date and time of transaction
}
Basically, i'm trying to make it so that when I go to enter a transaction, it checks that the AccountID that is entered for the transaction is equal to the AccountID from the HashMap (the key).
I tried using line 6 of the enterTransaction() to check whether it exists. However, it doesn't seem to work and always says "false" even when I know i have typed in the same accountID both times. I have also tried using this statement:
System.out.println(account.get(accountID));
This seems to give me "Account#cb1edc" ?
Sorry about the long question, it's a simple question really just thought i'd give you all the information I could. Thanks.
That is the correct behavior.
account.get(accountID) returns an Account object, which is being printed from the JVM memory dump.
To get some legible output, the Account class needs a toString method that returns a String with useful information.
When you try to print an object to the console, the JVM automatically searches for a toString method and uses that to stringify the object (make it humanly readable), if it cant find that method for the object it prints out the JVM's internal memory id for that object which looks a bit like garbage. Try this:
public String toString() {
return "This is account " + this.id; // or something like this
}