Trying to display all data from database table into Jtable using reflection - java

I'm trying to display all the data from different database table into a JTable using reflection but when i run the code I gen this kind of error:. The methods responsible for that are createViewAllQuery, ViewAll and createObjects from AbstractDAO class.
Any idea what the problem is? Thanks!
package project3;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import com.mysql.jdbc.PreparedStatement;
public class AbstractDAO<T>{
protected static final Logger LOGGER = Logger.getLogger(AbstractDAO.class.getName());
private final Class<T> type;
#SuppressWarnings("unchecked")
public AbstractDAO() {
this.type = (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
private String createFindQuery(String field) {
StringBuilder sb = new StringBuilder();
sb.append("SELECT ");
sb.append(" * ");
sb.append(" FROM ");
sb.append(type.getSimpleName());
sb.append(" WHERE " + field + "=?");
return sb.toString();
}
private String createAddQuery(T object) throws IllegalArgumentException, IllegalAccessException {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ");
sb.append(type.getSimpleName());
sb.append(" VALUES (");
for(Field field : object.getClass().getDeclaredFields()) {
field.setAccessible(true);
if(field.get(object) instanceof Integer) {
sb.append(field.get(object));
sb.append(",");
}
else {
sb.append("'");
sb.append(field.get(object));
sb.append("',");
}
}
sb.deleteCharAt(sb.length()-1);
sb.append(");");
System.out.println(sb.toString());
return sb.toString();
}
private String createViewAllQuery() throws IllegalArgumentException, IllegalAccessException {
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM ");
sb.append(type.getSimpleName());
sb.append(";");
return sb.toString();
}
public List<T> ViewAll() throws IllegalArgumentException, IllegalAccessException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
String query = createViewAllQuery();
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
resultSet = statement.executeQuery();
return createObjects(resultSet);
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findByFirstName " + e.getMessage());
} finally {
ConnectionFactory.close(resultSet);
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
return null;
}
public JTable createTable(List<T> objects) throws IllegalArgumentException, IllegalAccessException {
ArrayList<String> columnNamesArrayList = new ArrayList<String>();
for(Field field : objects.get(0).getClass().getDeclaredFields()) {
field.setAccessible(true);
columnNamesArrayList.add(field.getName());
}
String[] columnNames = new String[columnNamesArrayList.size()];
columnNames = columnNamesArrayList.toArray(columnNames);
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
Iterator<T> i = objects.iterator();
while(i.hasNext()) {
T object = i.next();
ArrayList<Object> columnDataAsArrayList = new ArrayList<Object>();
for(Field field : object.getClass().getDeclaredFields()) {
field.setAccessible(true);
columnDataAsArrayList.add(field.get(object));
}
Object[] columnDataAsArray = new Object[columnDataAsArrayList.size()];
columnDataAsArray = columnDataAsArrayList.toArray(columnDataAsArray);
tableModel.addRow(columnDataAsArray);
}
JTable table = new JTable(tableModel);
return table;
}
public void add(T object) throws IllegalArgumentException, IllegalAccessException {
Connection connection = null;
PreparedStatement statement = null;
String query = createAddQuery(object);
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
statement.executeUpdate();
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findByFirstName " + e.getMessage());
} finally {
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
}
public List<T> findByFirstName(String firstName) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
String query = createFindQuery("first_name");
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
statement.setString(1, firstName);
resultSet = statement.executeQuery();
return createObjects(resultSet);
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findByFirstName " + e.getMessage());
} finally {
ConnectionFactory.close(resultSet);
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
return null;
}
public T findById(int id) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
String query = createFindQuery("id");
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
statement.setInt(1, id);
resultSet = statement.executeQuery();
return createObjects(resultSet).get(0);
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findById " + e.getMessage());
} finally {
ConnectionFactory.close(resultSet);
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
return null;
}
private List<T> createObjects(ResultSet resultSet){
List<T> list = new ArrayList<T>();
try {
try {
while(resultSet.next()) {
T instance = type.newInstance();
for(Field field: type.getDeclaredFields()) {
Object value = resultSet.getObject(field.getName());
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), type);
Method method = propertyDescriptor.getWriteMethod();
method.invoke(instance, value);
}
list.add(instance);
}
} catch (IllegalAccessException | SecurityException | IllegalArgumentException | InvocationTargetException | SQLException | IntrospectionException e) {
e.printStackTrace();
}
}catch(InstantiationException e) {
e.printStackTrace();
}
return list;
}
}
package project3;
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.text.html.HTMLDocument.Iterator;
public class ProductsDAO extends AbstractDAO<Products>{
public ProductsDAO() {};
public static void main(String[] args) {
ProductsDAO p1 = new ProductsDAO();
//Products product1 = new Products(3, "cascaval", 5, " tip de branza facuta din lapte de vaca sau oaie", 4680);
try {
JTable table = new JTable();
table = p1.createTable(p1.ViewAll());
JFrame frame = new JFrame();
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
/*List<Products> list = new ArrayList<Products>();
list = p1.ViewAll();
java.util.Iterator<Products> i = list.iterator();
while(i.hasNext()) {
Products x = i.next();
System.out.println(x.getDescription());
}*/
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Here is one of the classes:
package project3;
public class Products {
private int id;
private String name;
private int price;
private String description;
private int stoc;
public Products(int id, String name, int price, String description, int stoc) {
super();
this.id = id;
this.name = name;
this.price = price;
this.description = description;
this.stoc = stoc;
}
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;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getStoc() {
return stoc;
}
public void setStoc(int stoc) {
this.stoc = stoc;
}
}

Your class Products hasn't got a default-constructor (so no method <init>), but you're trying to use that in
T instance = type.newInstance();
Since the Method isn't there the NoSuchMethodException is thrown.
You either have to add a default-constructor like
public Products() {
...
}
or call the constructor with arguments (probably harder to do ;)

Related

JdbcSQLSyntaxErrorException: Table "SPORTEVENT" not found; SQL statement, but why?

Im using h2 database for my application, and my task is to create and read queries as practice. The connection works fine, but the table is not found no matter what I try to do. My classes look like the following:
DB connection:
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DatabaseConnectionManager {
private final String url;
private final Properties properties;
public DatabaseConnectionManager(String host, String databaseName, String username,String password){
this.url = "jdbc:h2:mem://"+host+"/"+databaseName;
this.properties = new Properties();
this.properties.setProperty("username",username);
this.properties.setProperty("password",password);
}
public Connection getConnection() throws SQLException{
return DriverManager.getConnection(this.url,this.properties);
}
}
JDBCExecutor:
package database;
import dataaccess.SporteventDAO;
import domain.FootballSportEvent;
import java.sql.*;
import java.time.LocalDateTime;
public class JDBCExecutor {
public static void main(String[] args) {
DatabaseConnectionManager databaseConnectionManager= new DatabaseConnectionManager("localhost","jdbc:h2:mem:sports_betting","sa","");
try{
Connection connection = databaseConnectionManager.getConnection();
SporteventDAO sporteventDAO = new SporteventDAO(connection);
FootballSportEvent footballSportEvent = new FootballSportEvent();
footballSportEvent.setType("FootballSportEvent");
footballSportEvent.setId(2);
Date start = new Date(2022-07-06);
Date end = new Date(2022-07-07);
footballSportEvent.setStart(start);
footballSportEvent.setEnd(end);
footballSportEvent.setResultId(2);
sporteventDAO.create(footballSportEvent);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
SporteventDAO:
package dataaccess;
import domain.FootballSportEvent;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
public class SporteventDAO extends DataAccessObject<FootballSportEvent> {
private static final String INSERT = "INSERT INTO SPORTEVENT (DTYPE, ID, START, END, TITLE, RESULT_ID) VALUES (?,?,?,?,?,?)";
public SporteventDAO(Connection connection){
super(connection);
}
#Override
public FootballSportEvent findById(long id) {
return null;
}
#Override
public List<FootballSportEvent> findAll() {
return null;
}
#Override
public FootballSportEvent update(FootballSportEvent dto) {
return null;
}
#Override
public FootballSportEvent create(FootballSportEvent dto) throws SQLException {
try(PreparedStatement statement = this.connection.prepareStatement(INSERT);){
statement.setString(1,dto.getType());
statement.setInt(2,dto.getId());
statement.setDate(3, (Date) dto.getStart());
statement.setDate(4, (Date) dto.getEnd());
statement.setInt(5, dto.getResultId());
statement.execute();
}catch (SQLException e){
e.printStackTrace();
throw new RuntimeException(e);
}
return null;
}
#Override
public void delete(long id) {
}
}
DataTransferObject:
package dataaccess;
public interface DataTransferObject {
int getId();
}
DataAccessObject:
package dataaccess;
import org.h2.jdbc.JdbcConnectionBackwardsCompat;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
public abstract class DataAccessObject <T extends DataTransferObject>{
protected final Connection connection;
protected final static String LAST_VAL = "SELECT last_value FROM";
protected final static String CUSTOMER_SEQUENCE = "hp_customer_seq";
public DataAccessObject(Connection connection){
super();
this.connection =connection;
}
public abstract T findById(long id);
public abstract List<T> findAll();
public abstract T update(T dto);
public abstract T create(T dto) throws SQLException;
public abstract void delete(long id);
protected int getLastVal(String sequence){
int key = 0;
String sql = LAST_VAL + sequence;
try(Statement statement = connection.createStatement()) {
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
key = rs.getInt(1);
}
return key;
}catch (SQLException e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
FootballSportEventClass:
package domain;
import dataaccess.DataTransferObject;
import java.util.Date;
public class FootballSportEvent implements DataTransferObject
{
private String type;
private String name;
private int id;
private Date end;
private Date start;
private String title;
private int resultId;
public FootballSportEvent(){
}
public FootballSportEvent(String type, String name, int id, Date end, Date start, String title, int resultId) {
this.type = type;
this.name = name;
this.id = id;
this.end = end;
this.start = start;
this.title = title;
this.resultId = resultId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
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 Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getResultId() {
return resultId;
}
public void setResultId(int resultId) {
this.resultId = resultId;
}
#Override
public String toString() {
return "FootballSportEvent{" +
"type='" + type + '\'' +
", name='" + name + '\'' +
", id=" + id +
", end=" + end +
", start=" + start +
", title='" + title + '\'' +
", resultId=" + resultId +
'}';
}
}
And the following exception it thrown:
org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "SPORTEVENT" not found; SQL statement:
INSERT INTO SPORTEVENT (DTYPE, ID, START, END, TITLE, RESULT_ID) VALUES (?,?,?,?,?,?)
Edit:
I also tried using:
this.url = "jdbc:h2:mem://"+host+"/"+databaseName+";DB_CLOSE_DELAY=-1";
but it doesn't work.

Reuse the ResultSet and call in multiple classes in java

I have a method getalldetails (query) which will get details from the database. I want to call this method in multiple classes and based on query. It should fetch the data from the database. Query will be passed dynamically. I am trying to do in following way. Please correct me and advise me hwo to use only one method for data retrieval in whole project.
I am facing these issues:
Return type of result set and calling of method and re use of result. Please guide me and help me
For eg: In DatabaseDAO.java class
public class DatabaseDAO {
public static void main(String[] args) {
public ResultSet getalldetails(String query){
ResultSet rs = null;
try{
PreparedStatement stmt = con.prepareStatement(query);
rs = stmt.executeQuery();
}
catch (SQLException e){
e.printStackTrace();
}
return rs;
}
}
Suppose , I have two classes Employee and Product.java. I want to call this method in both classes . Below is my code:
public class Employee {
String query ="Select * from Employee";
ResultSet rs=null;
List<EmployeeDto> emp= new ArrayList<EmployeeDto>();
DatabaseDAO.getalldetails(query);
while (rs .has next)
{
EmployeeDto qd=new EmployeeDto();
qd.setidrs.getInt("id"));
qd.setname(rs.getString("name"));
qd.setrollno(rs.getString("rollno"));
emp.add(qd);
}
}
Similarly, I have Product.java . I want to call same method to retrieval data form DB based on query based.
public class Product {
String query ="Select * from Product";
ResultSet rs=null;
List<ProductDto> emp= new ArrayList<ProductDto>();
DatabaseDAO.getalldetails(query);
while (rs .has next)
{
ProductDto qd=new ProductDto();
pd.setidrs.getInt("prodid"));
pd.setname(rs.getString("prodname"));
pd.setrollno(rs.getString("item"));
prod.add(pd);
}
}
I want to use one method in whole project to retrieve the data from DB . Means I want to do reusability of method. Please help me on this.
You can make it a static method in a class. Say Database. And you can access it anywhere by importing the Database class and calling Database.getalldetails (query)
As an aside, i see in your code, that you have defined getalldetails inside the main method. You should put it outside.
In the Employee class, you place code inside a class, but outside a method/constructor. Add a Constructor or a method and put the code there
Well, This can be an example of your concept.
I call it a DBMain class which has a entry point of bot classes, the Product and the Employee class by the DatabaseDAO class.
First, make an instance of the DatabaseDAO class then initialize the database connection.
DatabaseDAO dbDAO = new DatabaseDAO();
dbDAO.initConnection();
Second, create both Employee and Product class with the DatabaseDAO instance as a parameter.
Employee emp = new Employee(dbDAO);
Product prd = new Product(dbDAO);
Finally, you can retrieve the data from both instance of class by calling methods, getEmployeeList and getProductList each then close the connection owned by the DAO class.
try {
emplist = emp.getEmployeeList();
prdlist = prd.getProductList();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
dbDAO.closeConnection();
}
The structure of the classes would be the same,
For example, the getProductList() looks:
public List<ProductDto> getProductList() throws SQLException {
ResultSet rs = null;
List<ProductDto> prd = new ArrayList<ProductDto>();
rs = dataDAO.getalldetails(query);
while (rs.next()) {
ProductDto qd = new ProductDto();
qd.setProdid(rs.getInt("prodid"));
qd.setProdname(rs.getString("prodname"));
qd.setItem(rs.getString("item"));
prd.add(qd);
}
rs.close();
return prd;
}
You can call getalldetails method in the DatabaseDAO instance and make the resultset a list of dto object.
The Employee and Product class:
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Employee {
private static final String query = "Select * from Employee";
final DatabaseDAO dataDAO;
Employee(final DatabaseDAO dataDAO) {
this.dataDAO = dataDAO;
}
public List<EmployeeDto> getEmployeeList() throws SQLException {
ResultSet rs = null;
List<EmployeeDto> emp = new ArrayList<EmployeeDto>();
rs = dataDAO.getalldetails(query);
while (rs.next()) {
EmployeeDto qd = new EmployeeDto();
qd.setId(rs.getInt("id"));
qd.setName(rs.getString("name"));
qd.setRollno(rs.getString("rollno"));
emp.add(qd);
}
rs.close();
return emp;
}
}
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Product {
private static final String query = "Select * from Product";
final DatabaseDAO dataDAO;
Product(final DatabaseDAO dataDAO) {
this.dataDAO = dataDAO;
}
public List<ProductDto> getProductList() throws SQLException {
ResultSet rs = null;
List<ProductDto> prd = new ArrayList<ProductDto>();
rs = dataDAO.getalldetails(query);
while (rs.next()) {
ProductDto qd = new ProductDto();
qd.setProdid(rs.getInt("prodid"));
qd.setProdname(rs.getString("prodname"));
qd.setItem(rs.getString("item"));
prd.add(qd);
}
rs.close();
return prd;
}
}
The Dao class - DatabaseDAO, this class has a structure only, you can make your connection object depending on databases.
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseDAO {
private Connection con;
public DatabaseDAO()
{
}
public void initConnection()
{
}
public Connection getDBConnection()
{
return con;
}
public void closeConnection()
{
try {
this.con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet getalldetails(String query) {
ResultSet rs = null;
try {
PreparedStatement stmt = con.prepareStatement(query);
rs = stmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
}
The main method class here:
import java.sql.SQLException;
import java.util.List;
public class DBMain {
public static void main(String[] args)
{
DatabaseDAO dbDAO = new DatabaseDAO();
dbDAO.initConnection();
Employee emp = new Employee(dbDAO);
Product prd = new Product(dbDAO);
List<EmployeeDto> emplist = null;
List<ProductDto> prdlist = null;
try {
emplist = emp.getEmployeeList();
prdlist = prd.getProductList();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
dbDAO.closeConnection();
}
}
}
Then, the dto classes left, EmpolyeeDto and ProductDto might be as follows:
public class EmployeeDto {
private int id;
private String name;
private String rollno;
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;
}
public String getRollno() {
return rollno;
}
public void setRollno(String rollno) {
this.rollno = rollno;
}
}
public class ProductDto {
private int prodid;
private String prodname;
private String item;
public int getProdid() {
return prodid;
}
public void setProdid(int prodid) {
this.prodid = prodid;
}
public String getProdname() {
return prodname;
}
public void setProdname(String prodname) {
this.prodname = prodname;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
}

Java WebService client wrongly generated

Well, first, sorry for my bad english.
I'm having a problem when generating a webservice.
I have my lib model, which contains the classes Endereco, Cidade e Cliente, and my DAO lib, which contains the database access classes for these models.
In Endereco.java class I have a private attribute Cidade cidade.
I have gotten a webservice to be a control between front end and back end.
The problem is that when I generate this webservice class "address" gets the int attribute city and not the attribute of my base class "Cidade".
Follow the codes of classes:
"ENDERECO.java":
package lib.modelo;
public class Endereco {
private int id;
private Cliente cliente;
private String endereco;
private String numero;
private String complemento;
private Cidade cidade;
private String bairro;
private String uf;
private String cep;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getComplemento() {
return complemento;
}
public void setComplemento(String complemento) {
this.complemento = complemento;
}
public Cidade getCidade() {
return cidade;
}
public void setCidade(Cidade cidade) {
this.cidade = cidade;
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getUf() {
return uf;
}
public void setUf(String uf) {
this.uf = uf;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
}
"CIDADE.java":
package lib.modelo;
public class Cidade {
private int id;
private String descricao;
private double valor_taxa;
public double getValor_taxa() {
return valor_taxa;
}
public void setValor_taxa(double valor_taxa) {
this.valor_taxa = valor_taxa;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
"ENDERECODAO.java":
package lib.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import lib.banco.ConexaoBanco;
import lib.modelo.Endereco;
public class EnderecoDAO {
private static final String CONSULTA_POR_ID = "SELECT * FROM cadastros.cliente_endereco WHERE id = ?;";
private static final String CONSULTA_POR_CLIENTE = "SELECT * FROM cadastros.cliente_endereco WHERE fK_cliente = ?;";
private static final String INSERE = "INSERT INTO cadastros.cliente_endereco ( fk_cliente , endereco , numero , complemento , fk_cidade , bairro , uf , cep) VALUES ( ?, ?, ?, ?, ?, ?, ?, ? );";
private static final String ALTERA = "UPDATE cadastros.cliente_endereco SET endereco = ?, numero = ?, complemento = ?, fk_cidade = ?, bairro = ?, uf = ?, cep = ? WHERE fk_cliente = ? AND id = ?;";
public List<Endereco> ConsultarEnderecoPorCliente (int codCliente) throws SQLException{
Connection conexaoSQL = null;
ResultSet rsEndereco = null;
List<Endereco> listaEndereco = new ArrayList<Endereco>();
ClienteDAO clienteDAO = new ClienteDAO();
CidadeDAO cidadeDAO = new CidadeDAO();
try{
conexaoSQL = ConexaoBanco.getConexao("selecao");
PreparedStatement pstmt = conexaoSQL.prepareStatement(CONSULTA_POR_CLIENTE);
pstmt.setInt(1, codCliente);
rsEndereco = pstmt.executeQuery();
while (rsEndereco.next()){
Endereco endereco = new Endereco();
endereco.setId(rsEndereco.getInt("id"));
endereco.setCliente(clienteDAO.CousultaPorId(rsEndereco.getInt("fk_cliente")));
endereco.setEndereco(rsEndereco.getString("endereco"));
endereco.setNumero(rsEndereco.getString("numero"));
endereco.setComplemento(rsEndereco.getString("complemento"));
endereco.setCidade(cidadeDAO.consultaPorId(rsEndereco.getInt("fk_cidade")));
endereco.setBairro(rsEndereco.getString("bairro"));
endereco.setUf(rsEndereco.getString("uf"));
endereco.setCep(rsEndereco.getString("cep"));
listaEndereco.add(endereco);
}
rsEndereco.close();
conexaoSQL.close();
}catch(Exception e){
conexaoSQL.close();
throw new RuntimeException(e);
}
return listaEndereco;
}
public boolean CadastrarEndereco (Endereco endereco) throws SQLException{
boolean status = false;
Connection conexaoSQL = null;
try {
conexaoSQL = ConexaoBanco.getConexao("insercao");
PreparedStatement pstmt = conexaoSQL.prepareStatement(INSERE);
pstmt.setInt(1, endereco.getCliente().getId());
pstmt.setString(2, endereco.getEndereco());
pstmt.setString(3, endereco.getNumero());
pstmt.setString(4, endereco.getComplemento());
pstmt.setInt(5, endereco.getCidade().getId());
pstmt.setString(6, endereco.getBairro());
pstmt.setString(7, endereco.getUf());
pstmt.setString(8, endereco.getCep());
pstmt.execute();
conexaoSQL.close();
status = true;
} catch (Exception e) {
conexaoSQL.close();
throw new RuntimeException(e);
}
return status;
}
public boolean AlterarEndereco (Endereco endereco) throws SQLException{
boolean status = false;
Connection conexaoSQL = null;
try {
conexaoSQL = ConexaoBanco.getConexao("alteracao");
PreparedStatement pstmt = conexaoSQL.prepareStatement(ALTERA);
pstmt.setString(1, endereco.getEndereco());
pstmt.setString(2, endereco.getNumero());
pstmt.setString(3, endereco.getComplemento());
pstmt.setInt(4, endereco.getCidade().getId());
pstmt.setString(5, endereco.getBairro());
pstmt.setString(6, endereco.getUf());
pstmt.setString(7, endereco.getCep());
pstmt.setInt(8, endereco.getCliente().getId());
pstmt.setInt(9, endereco.getId());
pstmt.execute();
conexaoSQL.close();
pstmt.close();
status = true;
} catch (Exception e) {
conexaoSQL.close();
throw new RuntimeException(e);
}
return status;
}
public Endereco ConsultarEnderecoPorId (int codEndereco) throws SQLException{
Connection conexaoSQL = null;
ResultSet rsEndereco = null;
Endereco endereco = new Endereco();
CidadeDAO cidadeDAO = new CidadeDAO();
ClienteDAO clienteDAO = new ClienteDAO();
try {
conexaoSQL = ConexaoBanco.getConexao("selecao");
PreparedStatement pstmt = conexaoSQL.prepareStatement(CONSULTA_POR_ID);
pstmt.setInt(1, codEndereco);
rsEndereco = pstmt.executeQuery();
if(rsEndereco.next()){
endereco.setBairro(rsEndereco.getString("bairro"));
endereco.setCep(rsEndereco.getString("cep"));
endereco.setCidade(cidadeDAO.consultaPorId(rsEndereco.getInt("fk_cidade")));
endereco.setCliente(clienteDAO.CousultaPorId(rsEndereco.getInt("fk_cliente")));
endereco.setComplemento(rsEndereco.getString("complemento"));
endereco.setEndereco(rsEndereco.getString("endereco"));
endereco.setId(rsEndereco.getInt("id"));
endereco.setNumero(rsEndereco.getString("numero"));
endereco.setUf(rsEndereco.getString("uf"));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
conexaoSQL.close();
rsEndereco.close();
return endereco;
}
}
And the WebService for ENDERECO "SERVICOENDERECO.java":
package lib.webservice.endereco;
import java.util.ArrayList;
import java.util.List;
import lib.dao.EnderecoDAO;
import lib.modelo.Cidade;
import lib.modelo.Cliente;
import lib.modelo.Endereco;
public class ServicoEndereco {
public Endereco[] consultaPorCliente(int id){
EnderecoDAO eDAO = new EnderecoDAO();
List< Endereco > listaEndereco = new ArrayList<Endereco>();
try{
listaEndereco = eDAO.ConsultarEnderecoPorCliente( id );
}catch(Exception e){
throw new RuntimeException(e);
}
return listaEndereco.toArray( new Endereco[0] );
}
public boolean cadastra( Cliente cliente , String logradouro , String numero ,
String complemento , Cidade cidade , String bairro ,
String uf , String cep){
boolean status = false;
try{
Endereco endereco = new Endereco();
EnderecoDAO eDAO = new EnderecoDAO();
endereco.setCliente(cliente);
endereco.setEndereco(logradouro);
endereco.setNumero(numero);
endereco.setComplemento(complemento);
endereco.setCidade(cidade);
endereco.setBairro(bairro);
endereco.setUf(uf);
endereco.setCep(cep);
status = eDAO.CadastrarEndereco(endereco);
}catch(Exception e){
throw new RuntimeException(e);
}
return status;
}
public boolean altera(Cliente cliente , String logradouro , String numero ,
String complemento , Cidade cidade , String bairro ,
String uf , String cep , int id){
boolean status = false;
try{
Endereco endereco = new Endereco();
EnderecoDAO eDAO = new EnderecoDAO();
endereco.setCliente(cliente);
endereco.setEndereco(logradouro);
endereco.setNumero(numero);
endereco.setComplemento(complemento);
endereco.setCidade(cidade);
endereco.setBairro(bairro);
endereco.setUf(uf);
endereco.setCep(cep);
endereco.setId(id);
status = eDAO.AlterarEndereco(endereco);
}catch(Exception e){
throw new RuntimeException(e);
}
return status;
}
public Endereco consultaPorId (int id){
EnderecoDAO eDAO = new EnderecoDAO();
Endereco endereco = new Endereco();
try {
endereco = eDAO.ConsultarEnderecoPorId(id);
} catch (Exception e) {
throw new RuntimeException(e);
}
return endereco;
}
}
Problem solved!
The difference between the classes was taking place due to my server configuration. When I updated the .jar files from the apache server classpath the code was generated properly.

How to get properties of an object stored in ArrayList using Java

I want to print all student objects' properties(name, subject, registrationNo) stored in a ArrayList object.
student details are getting from a database and insert them into student objects.
Then these student objects are insert into the ArrayList.
Finally I want to print these student object properties one by one as follows.
Followings are my codes.
DBconn.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBconn {
static Connection conn;
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/student_database", "root", "");
} catch (SQLException ex) {
}
} catch (ClassNotFoundException ex) {
}
return conn;
}
}
Student.java
public class Student {
private String name;
private String RegistrationNo;
private String course;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRegistrationNo() {
return RegistrationNo;
}
public void setRegistrationNo(String RegistrationNo) {
this.RegistrationNo = RegistrationNo;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
StudentList.java
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class StudentList {
public static ArrayList getStudentList() {
ArrayList list = new ArrayList();
String sql = "SELECT * FROM student";
try {
Statement stm = DBconn.getConnection().createStatement();
ResultSet rs = stm.executeQuery(sql);
while (rs.next()) {
Student student = new Student();
student.setName(rs.getString(1));
student.setCourse(rs.getString(2));
student.setRegistrationNo(rs.getString(3));
list.add(student);
}
} catch (SQLException ex) {
}
return list;
}
}
ViewStudent.java
public class ViewStudent {
public static void main(String[] args) {
int size = StudentList.getStudentList().size();
for (int i = 0; i < size; i++) {
System.out.println(StudentList.getStudentList().get(i));
//I want to get all student's name,subject and registrationNo
}
}
}
Thanks.
Simply give Student a public String toString() method override, one that returns a String holding all key properties, and then this will work fine:
System.out.println(StudentList.getStudentList().get(i));
Instead of System.out.println(StudentList.getStudentList().get(i));, you should access the student's properties and print it out.
Student s = (Student) StudentList.getStudentList().get(i);
System.out.println(s.getName());
System.out.println(s.getCourse());
System.out.println(s.getRegistrationNo());

What is the logic of creating the Mysql SELECT Statement for drop down in Struts + JSP?

can you please help me rectify the code below, I'm trying to create a populated drop down list in struts 2 in Eclipse as my IDE. This is my first time to use 'STRUTS' as well as 'IDE ECLIPSE'.
To be specific by the SELECT statement I do not know how to write the code that, when a user selects the 'Make' of the car, the database extracts the different 'Models' of that make. But other select items like 'Color', should be optional in that a user can proceed to search for the 'Make' minus choosing an option from them.
Please help I'm new in ActionClass and DataBase. Thanx in advance.
package drive;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.opensymphony.xwork2.ActionSupport;
public class CarSearch extends ActionSupport {
private String model;
private String modification;
private String engine;
private String color;
private String bodyType;
private String minPrice;
private String maxPrice;
private String mileage;
private int minYear;
private int maxYear;
private String make;
public String execute () {
String ret = NONE;
Connection conn = null;
try {
String URL = "jdbc:mysql://localhost/Cars";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, "root", "$jademedia247");
String sql = "SELECT make FROM type WHERE";
sql+=" model = ? AND modification = ? ";
PreparedStatement ps = conn.prepareStatement (sql);
ps.setString(1, model);
ps.setString(2, modification);
ResultSet rs = ps.executeQuery();
while (rs.next()){
make = rs.getString(1);
ret = SUCCESS;
}
} catch (Exception e) {
ret = ERROR;
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
return ret;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getModification() {
return modification;
}
public void setModification (String modification) {
this.modification = modification;
}
public String getEngine() {
return engine;
}
public void setEngine (String engine) {
this.engine = engine;
}
public String getColor() {
return color;
}
public void setColor (String color) {
this.color = color;
}
public String getBodyType() {
return bodyType;
}
public void setBodyType(String bodyType) {
this.bodyType = bodyType;
}
public String getMinPrice() {
return minPrice;
}
public void setMinPrice(String minPrice) {
this.minPrice = minPrice;
}
public String getMaxPrice () {
return maxPrice;
}
public void setMaxPrice (String maxPrice) {
this.maxPrice = maxPrice;
}
public String getMileage () {
return mileage;
}
public void setMileage (String mileage) {
this.mileage = mileage ;
}
public int getMinYear() {
return minYear;
}
public void setMinYear(int minYear) {
this.minYear = minYear;
}
public int getMaxYear() {
return maxYear;
}
public void setMaxYear(int maxYear) {
this.maxYear = maxYear;
}
public String getMake() {
return make;
}
public void setMake(String make){
this.make = make;
}
}
PreparedStatement ps = conn.prepareStatement ("SELECT field_name FROM table_name WHERE model = ? AND modification = ? ");
ps.setString(1, model);
ps.setString(2, modification);
ResultSet rs = ps.executeQuery();
//it will help you

Categories