Reading data from stored data in arraylist - java

Can someone help me i have those classes, and i want read out the getAllCustomer(), but i have no idea how i can implent it in my main method.
I tried already several things, but it didn't work well. Can anyone help me? :P
public static ArrayList<Customer> getAllCustomer() throws ClassNotFoundException, SQLException {
Connection conn=DBConnection.getDBConnection().getConnection();
Statement stm;
stm = conn.createStatement();
String sql = "Select * From Customer";
ResultSet rst;
rst = stm.executeQuery(sql);
ArrayList<Customer> customerList = new ArrayList<>();
while (rst.next()) {
Customer customer = new Customer(rst.getString("id"), rst.getString("name"), rst.getString("address"), rst.getDouble("salary"));
customerList.add(customer);
}
return customerList;
}
this is my model class
public class Customer {
private String id;
private String name;
private String salary;
private String address;
public Customer (String pId, String pName, String pSalary, String pAddress) {
id = pId;
name = pName;
salary = pSalary;
adress = pAddress;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

Assuming that your getAllCustomer() method is in class A . then in your main method, you do as follows
public void main(String[] args){
List<Customer> customers = A.getAllCustomer();
}
Based on the nature of your question, this JDBC tutorial will help you

The data type of your Salary field is String but you are getting the value as double.
All you need to do is to change the rst.getDouble("salary") to rst.getString("salary")
To call the method:
public static void main(String[] args)
ArrayList<Customer> customers = YourDALClass.getAllCustomer();
for(Customer c : customers){
System.out.println(c.getName());
}
}

Related

How to define Ignite Caches for objects Joined from Multiple Tables

I am working with Postgres set up as an external persistent store for Ignite and want to know what ways there are to define caches for objects who’s data is spread over multiple tables.
E.G. for to work with this Person and Car class and their tables below, I have provided my own Implementation of the CacheStore. This approach seems to be very verbose however as I need to manually assign the field values myself. Are there any other methods I could be using to do this?
Person Class:
public class PersonMO{
private int id;
private String name;
private String address;
private Set<Car> cars
public PersonMO() {};
public PersonMO(int id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString() {
return "ID: "+id +", Name: "+name+" AD: " +address;
}
public void setCars(Set<Car> cars) {
this.cars = cars;
}
public Set<Car> getCars() {
return cars;
}
}
Car Class
public class Car {
int id;
private String name;
public Car(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
CacheStore implmentation
public class PersonMOCacheStore implements CacheStore<Integer, PersonMO>{
#SpringResource(resourceName = "pgDataSource")
private DriverManagerDataSource pgDataSource;
#LoggerResource
private IgniteLogger log;
//public void loadCache(IgniteBiInClosure<Integer, PersonMO> clo, #Nullable Object... args)
#Override
public void loadCache(IgniteBiInClosure<Integer, PersonMO> clo, Object... args)
throws CacheLoaderException {
log.info(">> Loading cache from store...");
try(Connection conn = pgDataSource.getConnection()){
try(PreparedStatement st = conn.prepareStatement("select * from PERSON")){
try(ResultSet rs = st.executeQuery()){
while(rs.next()) {
PersonMO person = new PersonMO(rs.getInt(1),rs.getString(2), rs.getString(3));
person.setCars(getCarSet(conn, person.getId() ) );
clo.apply(person.getId(), person);
}
log.info(">> Finished Loading cache from store...");
}
}
}catch(SQLException e) {
throw new CacheLoaderException("Failed to load values from cache store.",e);
}
}
//implementation for IgniteCache.get
#Override
public PersonMO load(Integer key) throws CacheLoaderException {
log.info(">> Loading person from store...");
try (Connection conn = pgDataSource.getConnection()) {
try(PreparedStatement st = conn.prepareStatement("select * from PERSON where id = ?")){
st.setString(1, key.toString());
ResultSet rs = st.executeQuery();
if(rs.next()) {
PersonMO p= new PersonMO(rs.getInt(1),rs.getString(2), rs.getString(3));
//p.setCars( getCarSet(conn, p.getId() ) );
return p;
}else {
return null;
}
}
}catch(SQLException e) {
throw new CacheLoaderException("Failed to load values from cache store.",e);
}
}
private Set<Car> getCarSet(Connection conn, int personId) throws SQLException{
Set<Car> carSet = new HashSet<Car>();
PreparedStatement st = conn.prepareStatement("select * from CAR where id = "+ personId);
ResultSet rs = st.executeQuery();
while(rs.next()) {
carSet.add(new Car(rs.getInt(1),rs.getString(2) ));
}
return carSet;
}
//other methods needed left out for sake of simplicity
}
You can use CacheJdbcPojoStore to populate caches. Then the data may be accessed via SQL or key/value APIs.
However, it's not much less verbose :)
https://www.gridgain.com/docs/latest/developers-guide/persistence/external-storage#cachejdbcpojostore

The value of the field is not used

public class Client {
private String idNum;
private int driverLicence;
private String name;
private String surname;
private String mailAddress;
private String address;
private int phoneNum;
public Client(String idNum, int driverLicence, String name, String surname, String mailAddress, String address, int phoneNum) {
this.address=address;
this.driverLicence=driverLicence;
this.idNum=idNum;
this.mailAddress=mailAddress;
this.name=name;
this.phoneNum=phoneNum;
this.surname=surname;
}
public String getIdNum() {
return idNum;
}
public void setIdNum(String idNum) {
this.idNum = idNum;
}
public int getDriverLicence() {
return driverLicence;
}
public void setDriverLicence(int driverLicence) {
this.driverLicence = driverLicence;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getMailAddress() {
return mailAddress;
}
public void setMailAddress(String mailAddress) {
this.mailAddress = mailAddress;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
this.address = address;
}
public int getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(int phoneNum) {
this.phoneNum = phoneNum;
}
}
THE VALUE OF THE FIELD Client.idNum IS NOT USED
for some reason i am getting this kind of error on every field i have written on this class
ALL getters and setters are generated from eclipse
and all my other classes are fine but for some reason this specific class gives this "error"
i have wasted a lot of time on this and can't seem to find the reason why this happends
any ideas?
I copy pasted my code in, and an issue that may be causing your problem is that the code below returns the incorrect instance variable. Your instance variable is "address" not "Address".
public String getAddress() {
return Address;
}

deep cloning with out serialization

I am very new and learning java,I want to perform deep cloning without serialization ,I read some articles from internet and still in doubt about deep cloning without serialization.So i want to know is there any other rules that I have to follow to do deep cloning, below is my program
Department.java
package com.deepclone;
public class Department {
private int id;
private String name;
public Department(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Employee.java
package com.deepclone;
public class Employee implements Cloneable {
private String employeeId;
private String empName;
private Department department;
public Employee(String employeeId, String empName, Department department) {
this.employeeId = employeeId;
this.empName = empName;
this.department = department;
}
#Override
protected Object clone() throws CloneNotSupportedException {
Employee employee = new Employee(employeeId, empName, new Department(
department.getId(), department.getName()));
return employee;
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
TestCloning.java
package com.deepclone;
public class TestClonning1 {
public static void main(String[] args) throws CloneNotSupportedException {
Department hrDepartment = new Department(10, "HR");
Employee employee = new Employee("1", "rajeev", hrDepartment);
System.out.println(employee.getDepartment().getName());
Employee cloneEmployee = (Employee) employee.clone();
System.out.println(cloneEmployee.getDepartment().getName());
cloneEmployee.getDepartment().setName("it");
System.out.println(employee.getDepartment().getName());
System.out.println(cloneEmployee.getDepartment().getName());
}
}
output
HR
HR
HR
it
is there any other alternative to achive deep cloning without serialization...if yes then give link.
Try this Java Deep-Cloning Library
Cloner cloner = new Cloner();
MyClass other = ...;
MyClass clone = cloner.deepClone(other);

LinkedList && Servlet

`I am a new to java and to servlet topic.
I write a little web application. it's collect some data from web-form and add it into a LinkedList.
But my debugger shown me that adding to LL doesnt occur. HELP PLEASE!
Here some code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String surname = request.getParameter("surname");
String fatherName = request.getParameter("fathername");
String department = request.getParameter("department").toLowerCase();
Integer age = Integer.valueOf(request.getParameter("age"));
System.out.println(name);
System.out.println(surname);
System.out.println(fatherName);
responseToUser(addEmployee(name,surname,fatherName,department, age),response);
}
public boolean addEmployee(String name, String surname, String fathername, String department, Integer age) {
AllWorkers workers = new AllWorkers();
if (!name.equals("") && !surname.equals("") && !fathername.equals("") && !dep artment.equals("") && age != null) {
Person person = new Person(surname, name, fathername, department, age);
Departments dep = Departments.valueOf(person.getDepartment());
if (dep == Departments.логистика) {
workers.addLogistic(person);
} else if (dep == Departments.продажи) {
workers.addSales(person);
}
return true;
} else {
return false;
}
}
public void responseToUser(boolean boo, HttpServletResponse response) throws IOException {
Gson gson = new Gson();
response.setContentType("application/json");
if(boo == true){
response.getWriter().write(gson.toJson(true));
}else if(boo == false){
response.getWriter().write(gson.toJson(false));
}
}
Departments:
public enum Departments {
логистика,продажи
}
AllWorkers.java
public class AllWorkers {
LinkedList<Person> logistic = new LinkedList<Person>();
LinkedList<Person> sales = new LinkedList<Person>();
public void addLogistic(Person person){
logistic.add(person);
}
public void addSales(Person person){sales.add(person);}
public LinkedList<Person> getLogistic() {
return logistic;
}
public LinkedList<Person> getSales() {
return sales;
}
}
Person.java
public class Person {
private String name;
private String surname;
private String fatherName;
private String department;
private int age;
Person(){
}
Person(String name, String surname, String fatherName,String department, int age){
this.name = name;
this.surname = surname;
this.fatherName = fatherName;
this.department = department;
this.age = age;
}
public String getDepartment() {
return department;
}
public String getFatherName() {
return fatherName;
}
public int getAge() {
return age;
}
public String getSurname() {
return surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setFatherName(String fatherName) {
this.fatherName = fatherName;
}
public void setSurname(String surname) {
this.surname = surname;
}
public void setDepartment(String department) {
this.department = department;
}
}
(I assume you have checked your variables name, surname, fatherName, department and age have correct values)
I have tested your code and persons are added to LinkedLists contained in AllWorkers correctly. However, in method addEmploye() you do this:
AllWorkers workers = new AllWorkers();
which means you create a new workers every time you comsume the servlet, and each time that workers will be empty since it's a new object. Maybe that is the reason it seems that persons are not added to lists.
Regards,

Customized JAXB xml output

Given the following class:
public class Customer {
public String name;
public String lastName;
}
I want to generate the following xml output using JAXB for a customer whose name is John and lastName is Doe:
<cst>John Doe</cst>
How can i do this with JAXB?
EDIT
The class Customer is used in several places, as shown here:
public class Sale {
private String productId;
private Date date;
private Customer customer;
}
public class Transaction {
private List<Sale> sales;
}
... and so on... The deal is, how can I tell JAXB: "whenever you see a customer, please use custom formatting"?
My problem is that there are many classes that contain a customer, and I want to programatically control the output (sometimes name + lastname, sometimes <name>name</name>, <lastname>lastname</lastname>) without adding annotations at every class that contains Customer. This requirement would rule out using JAXBElement<Customer>.
You could install an XmlAdapter that handles the translation:
public static void main(String[] args) throws Exception {
JAXBContext ctxt = JAXBContext.newInstance(CustomerWrapper.class);
Marshaller m = ctxt.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
Customer customer = new Customer("John", "Doe");
m.marshal(new JAXBElement<CustomerWrapper>(new QName("cwrapper"), CustomerWrapper.class, new CustomerWrapper(customer)), System.err);
}
static class CustomerWrapper {
private Customer customer;
public CustomerWrapper() {
}
public CustomerWrapper(Customer customer) {
this.customer = customer;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
#XmlJavaTypeAdapter(CustomerAdapter.class)
static class Customer {
private String name;
private String lastName;
public Customer() {
}
public Customer(String name, String lastName) {
this.name = name;
this.lastName = lastName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
static class CustomerAdapter extends XmlAdapter<String, Customer> {
#Override
public Customer unmarshal(String v) throws Exception {
String[] ss = v.split(" ");
return new Customer(ss[0], ss[1]);
}
#Override
public String marshal(Customer v) throws Exception {
return v.getName() + " " + v.getLastName();
}
}
outputs
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cwrapper>
<customer>John Doe</customer>
</cwrapper>

Categories