Spring MVC Preparedstatementcreator : local variable object is accessed from inner class - java

I'm trying to save a Customer record here, using preparedstatementcreator.
public Customer saveRecord(Customer customer) {
int result = 0;
try {
KeyHolder keyHolder = new GeneratedKeyHolder();
result = jdbcTemplate.update(new PreparedStatementCreator() {
#Override
public PreparedStatement createPreparedStatement(Connection connection)
throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(SQL_INSERT_CUSTOMER_MASTER_WITH_AUTO_INCREMENT, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, customer.getFirstname());
return preparedStatement;
}
}, keyHolder);
} catch (DataAccessException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result > 0 ? customer : null;
}
And here is my Customer object.
public class Customer implements Serializable{
private long id;
private String firstname;
private String secondname;
private int age;
private String address;
private Country country;
private String[] language;
public Customer() {
}
public Customer(String firstname, String secondname, int age, String address, Country country, String[] language) {
this.firstname = firstname;
this.secondname = secondname;
this.age = age;
this.address = address;
this.country = country;
this.language = language;
}
//getters setters
}
I understand the reason here is we cannot access customer object from inside of createPreparedStatement().
So kind of modification I can do to original Customer object class to make it visible inside of this inner class?

Related

Getting an SQL syntax error doesn't when trying to do GET REQUEST

Hello I'm trying to display the Student data with his corresponding subject based on the subject_id foreign key and displaying the result on GET REQUEST. I don't know how I need to rewrite the SQL command to remove the error. Here is the Error:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN subject ON student.subject_id=subject.id WHERE user_id=3' at line 1Retrieve not successful
Here is my DB schema:
Here is my code:
public ArrayList<Object> getStudentSubject(int id) throws Exception {
Connection connection = null;
ArrayList<Student> data = new ArrayList<>();
ArrayList<Subject> data2=new ArrayList<>();
ArrayList<Object> data3 = new ArrayList<>();
try {
connection = new MysqlDbConnectionService().getConnection();
String select ="SELECT student.user_id, student.username, student.password, student.fullname,student.email, subject.id,subject.name" +
"FROM student INNER JOIN subject ON student.subject_id=subject.id WHERE user_id=?";
PreparedStatement ps = connection.prepareStatement(select);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
Student model = new Student();
Subject model2 = new Subject();
while (rs.next()) {
model.setId(rs.getString("user_id"));
model.setUsername(rs.getString("username"));
model.setPassword(rs.getString("password"));
model.setFullName(rs.getString("fullname"));
model.setEmail(rs.getString("email"));
model2.setId(rs.getInt("id"));
model2.setName(rs.getString("username"));
data.add(model);
data2.add(model2);
data3.add(data);
data3.add(data2);
}
} catch (Exception e) {
System.out.println(e + "Retrieve not successful");
}
return data3;
}
Jersey Code:
#Path("subject/{id}")
#GET
public Response getStudentwithSubject(#PathParam("id") int id) throws Exception {
return Response.ok(new Gson().toJson(studentService.getStudentSubject(id))).build();
}
Student Model:
package com.common.db.domain;
import com.google.gson.annotations.SerializedName;
public class Student {
#SerializedName("id")
private String id;
#SerializedName("username")
private String username;
#SerializedName("password")
private String password;
#SerializedName("fullname")
private String fullName;
#SerializedName("email")
private String email;
public Student()
{
}
public Student(String id, String username, String password, String fullName, String email)
{
super();
this.id=id;
this.username = username;
this.password = password;
this.fullName = fullName;
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Subject Model:
package com.common.db.domain;
import com.google.gson.annotations.SerializedName;
public class Subject {
#SerializedName("id")
private int id;
#SerializedName("name")
private String name;
public Subject() {
this.id = id;
this.name=name;
}
public void setId(int id)
{
this.id=id;
}
public int getId()
{
return id;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
}
It is a simply wrong SQL formed because of string concatenation, if you observe there is no space between subject.name and FROM student. Add space either after subject.name or before FROM like below.
String select ="SELECT student.user_id, student.username, student.password, student.fullname,student.email, subject.id,subject.name " +
" FROM student INNER JOIN subject ON student.subject_id=subject.id WHERE user_id=?";
Let me know if this helps.

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

MySQLIntegrityConstraintViolationExceptionnnn

Here is a code:
#Override
public Article insert(Article article,String sql) {
try {
pr = super.get(sql);
pr.setInt(1, article.getId());
pr.setString(2, article.getName());
pr.setString(3, article.getDescription());
pr.setString(4, article.getAuthor());
pr.setString(5, article.getPicture_url());
pr.setDouble(6, article.getPrice());
pr.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
DbHandler.showErrorMessage(e);
}
return article;
}
#XmlRootElement
public class Article {
private String name;
private String description;
private String picture_url;
private String author;
private int id;
private double price;
public Article() {
// TODO Auto-generated constructor stub
}
public Article(String name, String description, String picture_url, String author, int id, double price) {
super();
this.name = name;
this.description = description;
this.picture_url = picture_url;
this.author = author;
this.id = id;
this.price = price;
}
public String getAuthor() {
return author;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getPicture_url() {
return picture_url;
}
public int getId() {
return id;
}
public double getPrice() {
return price;
}
}
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Article insert(Article article) {
return repo.insert(article, "insert into book values (?, ? , ? , ? , ? , ?)");
}
When i try to insert the Article in database with POST method every time i have MySQLIntegrityConstraintViolationException and the message is 'name can not be null'? Can someone help me what is the problem here?
And also i have database table with two primary keys with id and name
This is a screenshot in postman
enter image description here

Java: I'm having an issue connecting to a database from another class

I'm making a simple address book app. I have a DatabaseUtility class, which has one method, connectToDatabase() is responsible for pulling info from an embedded database (Java DB) and constructing Contact objects from it.
These Contact objects are then placed into an ArrayList and then the entire ArrayList is returned. Yes, I know this is poor programming. It makes more logical sense to have separate methods for connecting and constructing objects, but this is kind of a quick little project I'm doing for practice, and I think I can get by, right?
Anyways, I also have a ContactControl class which contains an instance of the DatabaseUtility class as one of it's fields, as well as a private ArrayList of Contacts as one of it's fields.
What I want is for the ArrayList in the ContactControl class to be instantiated by the return value of the connectToDatabase() method (which, as I've already mentioned, returns an ArrayList).
However, I keep getting an exception. It's not connecting to the database. It connects when I run the main method that I placed in the DatabaseUtility class, but when I run the main method from the ContactControl class, I get an exception.
My code is below:
Contact class:
package contactbook;
import java.io.IOException;
import java.io.ObjectStreamException;
import java.util.Date;
public class Contact {
private int contactId;
private String lastName;
private String firstName;
private String address;
private String city;
private String state;
private String zip;
private String picture;
private String dob;
public Contact()
{
contactId = 0;
lastName = "Doe";
firstName = "John";
dob = "01/01/1997";
address = "123 ABC Dr.";
city = "Pensacola";
state = "FL";
zip = "12345";
picture = "default1.gif";
}
public Contact(int contactId, String lastName, String firstName, String address, String city, String state, String zip, String picture, String dob)
{
this.contactId = contactId;
this.lastName = lastName;
this.firstName = firstName;
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
this.picture = picture;
this.dob = dob;
}
//setters
public void setContactId(int contactId)
{
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public void setAddress(String address)
{
this.address = address;
}
public void setCity(String city)
{
this.city = city;
}
public void setState(String state)
{
this.state = state;
}
public void setZip(String zip)
{
this.zip = zip;
}
public void setPicture(String picture)
{
this.picture = picture;
}
public void setDob(String dob)
{
this.dob = dob;
}
//getters
public int getContactId()
{
return contactId;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
public String getAddress()
{
return address;
}
public String getCity()
{
return city;
}
public String getState()
{
return state;
}
public String getZip()
{
return zip;
}
public String getPicture()
{
return picture;
}
public String getDob()
{
return dob;
}
}
DatabaseUtility class:
package contactbook;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.DatabaseMetaData;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Properties;
public class DataBaseUtility {
public ArrayList<Contact> connectToDatabase() throws Exception {
ArrayList<Contact> contacts = new ArrayList<Contact>();
try
{
// Step 1: "Load" the JDBC driver
Class.forName("org.apache.derby.jdbc.ClientDriver");
// Step 2: Establish the connection to the database
String url = "jdbc:derby://localhost:1527/ContactBook";
Connection conn = DriverManager.getConnection(url,"app","app");
System.out.println("Connected!");
Statement stat = null;
stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM PERSON");
int id = 1;
while(rs.next())
{
Contact contact = new Contact();
contact.setContactId(id);
System.out.println(id);
String lastName = rs.getString("lastName");
System.out.println(lastName);
contact.setLastName(lastName);
String firstName = rs.getString("firstName");
System.out.println(firstName);
contact.setFirstName(firstName);
String address = rs.getString("address");
System.out.println(address);
contact.setAddress(address);
String city = rs.getString("city");
System.out.println(city);
contact.setCity(city);
String state = rs.getString("state");
System.out.println(state);
contact.setState(state);
String zip = rs.getString("zip");
System.out.println(zip);
contact.setZip(zip);
String picture = rs.getString("picture");
System.out.println(picture);
contact.setPicture(picture);
Date dob = rs.getDate("dob");
System.out.println(dob);
contact.setDob("" + dob);
contacts.add(contact);
System.out.println("");
contacts.add(contact);
id++;
}
}
catch (Exception e)
{
System.err.println("D'oh! Got an exception!");
System.err.println(e.getMessage());
}
return contacts;
}
public static void main(String[] args)
{
DataBaseUtility dbu = new DataBaseUtility();
try
{
dbu.connectToDatabase();
}
catch(Exception e)
{
e.getMessage();
}
}
}
ContactControl class:
package contactbook;
import java.util.ArrayList;
public class ContactControl {
private DataBaseUtility dbu;
private ArrayList<Contact> contacts;
public ArrayList<Contact> createContacts() throws Exception
{
try
{
contacts = dbu.connectToDatabase();
}
catch(Exception e)
{
System.out.println("Error!");
}
return contacts;
}
public Contact getContact(int id)
{
Contact tact = new Contact();
for(Contact c : contacts)
{
if(id == c.getContactId())
{
tact = c;
}
}
return tact;
}
public static void main(String[] args)
{
ContactControl cc = new ContactControl();
ArrayList<Contact> tacts = new ArrayList<>();
try
{
tacts = cc.createContacts();
}
catch(Exception e)
{
System.out.println("Uh oh! Problem!");
}
}
}
Whenver I run the main method of the ContactControl class, I get the "Error!" message that you see in the try-catch block.
I think the issue is that you're calling a null object in your ContactControl class.
contacts = dbu.connectToDatabase();
dbu is not initialized and basically it's null thus the NullPointerException. Since you're hiding actual exception messages from yourself with some custom messages you wouldn't see it.

Reading data from stored data in arraylist

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());
}
}

Categories