samedi 14 avril 2018

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

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:enter image description here. The methods responsible for that are createViewAllQuerry, ViewAll and createObjects from AbstractDAO class.

Any ideea 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 createFindQuerry(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 createAddQuerry(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 createViewAllQuerry() 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 = createViewAllQuerry();
            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> collumnNamesArrayList = new ArrayList<String>(); 
            for(Field field : objects.get(0).getClass().getDeclaredFields()) {
                field.setAccessible(true);
                collumnNamesArrayList.add(field.getName());
            }
            String[] columnNames = new String[collumnNamesArrayList.size()];
            columnNames = collumnNamesArrayList.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 = createAddQuerry(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 = createFindQuerry("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 = createFindQuerry("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;
    }
}





Aucun commentaire:

Enregistrer un commentaire