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
Related
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
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.
I using redis caching my project but i have a problem. I had model student and write method put it to redis.First method i write findStudent one week and put it to cache.
public void findStudentOneWeek(List<Student> students1) {
redistemplate.opsForHash().put("Student", student.getId(), List<Customers>);
}
Second method I write findStudent one day.
public void findStudentOneDay(List<Student> students2) {
redistemplate.opsForHash().put("Student", student.getId(), List<Customers>);
}
But i want total user from 8 day. It mean i want hold one key Student but new value equal total value method findStudentOneWeek + total value method findStudentOneDay. But i don't now how to do. I can't find method working it. I know method put from redis but it remove old value and save new value. I don't want it. I want value total.
Firstly, I assume a typo, where List<Customers> should be List<Students> student:
redistemplate.opsForHash().put("Student", student.getId(), List<Students> students);
Spring Data class HashOperations works on the similar principle as HashMap. Both allow you to get the value by the key (and the hash key in case of HashOperations). Read the current value List<Customers> and put them with a new value to the template.
List<Students> students = redistemplate.opsForHash().get("Student", student.getId());
students2.addAll(students);
redistemplate.opsForHash().put("Student", student.getId(), students2);
This is my sample mapping in hibernate
class ApplnDoc {
AdmAppln admAppln;
// getters and setters
}
class AdmAppln {
Set<Student> student;
// getters and setters
}
class Student {
int id;
String registerNo;
AdmAppln admAppln;
// getters and setters
}
In ApplnDoc table we are storing images of all candidates. AdmAppln is for storing admission details, Student is for storing student details. Even if AdmAppln is having a Set of Student, only one record of Student will be present for a particular AdmAppln id (under one AdmAppln only one Student).
Now I want to write few data from to these tables, into an Excel file, whose records must be sorted in the order of registerNo (if it is present), otherwise using id of the Student. We are using XSSFWorkbook class under org.apache.poi.xssf.usermodel package for doing operations on Excel sheet. Here I found a way to sort the excel sheet, but I tried and found a way in code itself using Comparable interface.
This is what I did in ApplnDoc class
public int compareTo(ApplnDoc otherData) {
if(new ArrayList<Student>(this.admAppln.getStudents()).get(0).getRegisterNo() != null &&
!new ArrayList<Student>(this.admAppln.getStudents()).get(0).getRegisterNo().isEmpty() &&
new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getRegisterNo() != null &&
!new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getRegisterNo().isEmpty()) {
return new ArrayList<Student>(this.admAppln.getStudents()).get(0).getRegisterNo()
.compareTo
(new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getRegisterNo());
} else {
return new ArrayList<Student>(this.admAppln.getStudents()).get(0).getId() -
new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getId();
}
}
Since there is no get() method in Set interface the only way to get Student's registerNo from AdmAppln was to convert it to a list. Then I sorted the list and then it was iterated to generate the excel file.
Is the above mentioned comparison mechanism a proper one or is there a better way? Why I am asking this question because when the Hibernate session is closed and in my compareTo if I'm accessing the child table columns, then I will be getting Invocation exception.
There are some thing worth discussing here:
1-
Even if AdmAppln is having a Set of Student, only one record of
Student will be present for a particular AdmAppln
Why?
is this something you have no control over or is there any particular reason to keep a set where is not needed? (also im assuming a #OneToMany instead of a #OneToOne mapping)
2-
This lead to the child object beig lazy fetched (N.B this is an assumption since you didn't post relevant code about mappings or how you fetch the entity from db).
This means that you have to either switch to eager fetching in the entity (unrecommended) or specify it when fetching the entities
3-
Also please refactor that compareTo and use variables
public int compareTo(ApplnDoc otherData) {
Student thisStudent = new ArrayList<>(this.admAppln.getStudents()).get(0);
Student otherStudent = new ArrayList<>(otherData.admAppln.getStudents()).get(0);
if(thisStudent.getRegisterNo() != null &&
!thisStudent.getRegisterNo().isEmpty() &&
otherStudent.getRegisterNo() != null &&
!otherStudent.getRegisterNo().isEmpty()) {
return thisStudent.getRegisterNo().compareTo(otherStudent.getRegisterNo());
} else {
return thisStudent.getId() - otherStudent.getId();
}
}
While nothing wrong with that comparison mechanism (except the NullPointer if you have an empty Set of student) you should use the database ordering when querying.
If you still want to compare that way you just have to make sure you have everything you need fetched before closing the session.
You need to load the entire object tree before closing the session else you will get Exception. By the way you can always sort records with the query itself.
I have an Array of objects. Each object is a customer record, which is the customer ID (int), first name (String), last name(String), and balance (double).
My problem is that i am not supposed to have duplicate customer records, so if they appear in the file twice, I have to just update their balance. I cannot figure out how to search the array to find out if i need to just update the balance or make a new record in the array.
I feel like i should do this in the get/setters, but i am not exactly sure.
edit: to clarify on "if they appear in the file twice, I have to just update their balance." I have a file i made in notepad which is supposed to be a customer list, which has all of their information. if the same customer shows up twice, say the following day to buy more stuff, i am not supposed to create a new object for them since they already have an object and a place in the array. instead, i am supposed to take the amount they spent, and add it to their already existing balance within their existing object.
edit2: i thought i would give you the bit of code i have already where i read in the values into the array. i based this off of the example we did in class, but we didn't have to update anything, just store information into an array and print it if needed.
public CustomerList(){
data = new CustomerRecord[100]; //i'm only allowed 100 unique customers
try {
Scanner input = new Scanner(new File("Records.txt"));
for(int i = 0; i < 100; ++i){
data[i] = new CustomerRecord();
data[i].setcustomerNumber(input.nextInt());
data[i].setfirstName(input.next());
data[i].setlastName(input.next());
data[i].setTransactionAmount(input.nextDouble());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
You shouldn't be using arrays in that case. A Set would be much more suitable as it, by definition, does not have duplicate entries.
What you need to do is to implement the equals() and hashCode() methods in your Customer class so they only use id (or id and name fields) but not balance.
If for some reason you need to use arrays you have two options:
sort the array and use binary search to find if the customer is there, this is nice if the array doesn't change much but you're doing a lot of updates
simply do a linear scan of the array, checking each entry to see if a given customer is already there, if so then update the balance, otherwise add it as a new entry
It would be something like:
public void updateOrAdd(Customer cst) {
boolean exists = false;
for(Customer existing : array) {
// !!! You need to implement your own equals method in the
// customer so it doesn't take into account the balance !!!
if(existing.equals(cst)) {
exists = true;
existing.updateBalance(cst.getBalance());
break;
}
}
if(!exists) {
// add the cst to the array
}
}
The difference is in runtime, the set solution will be constant O(1) on average (unless you incorrectly implement your hashCode() method).
Suppose you have a Customer array:
Customer[] customers = new Customer[size];
... // fill the array with data
Then you get a new customer object called newCustomer. You need to search for newCustomer in your array and, update it if it is already there, or add it if it's not. So you can do something like this:
// Return, if it exists, a customer with id equal to newCustomer.getId()
Optional<Customer> existingCustomer =
Arrays.stream(customers)
.filter(c -> newCustomer.getId().equals(c.getId()))
.findFirst();
if (existingCustomer.isPresent()) {
// update the customer object with newCustomer information as appropriate
Customer customer = existingCustomer.get();
// assuming you have an updateBalance() method
customer.updateBalance(newCustomer.amountSpent());
} else {
// if the customer is not in the array already, add them to the current position
customers[currentIndex] = newCustomer;
}