gpt4 book ai didi

java - 尝试使用反射将数据库表中的所有数据显示到 Jtable 中

转载 作者:行者123 更新时间:2023-11-30 06:13:03 26 4
gpt4 key购买 nike

我试图使用反射将不同数据库表中的所有数据显示到 JTable 中,但是当我运行代码时,我生成了这种错误:enter image description here 。负责此操作的方法是 AbstractDAO 类中的 createViewAllQuery、ViewAll 和 createObjects。

知道问题是什么吗?谢谢!

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

这是其中一类:

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

最佳答案

您的类(class)Products没有默认构造函数(因此没有方法 <init> ),但您尝试在

中使用它
T instance = type.newInstance();

由于该方法不存在 NoSuchMethodException被抛出。

您要么必须添加一个默认构造函数,例如

public Products() {
...
}

或者用参数调用构造函数(可能更难做到;)

关于java - 尝试使用反射将数据库表中的所有数据显示到 Jtable 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49831334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com