有了这个类 ,基本后台的所有逻辑操作都能实现,后端雏形就算搭建出来了
说说写这个类遇到的坑
1。Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 6
ResultSetMetaData中的getColumnCount()方法是从1开始的
代码如下:
resultSet = DbHelper.getStatement().executeQuery(sql);
ResultSetMetaData data = resultSet.getMetaData();
int columnsCount = data.getColumnCount();
for (int i = 1; i <= columnsCount; i++) {
String s = data.getColumnName(i);
list.add(s);
}
2。这些代码都实现了所需要的功能,但是没有优化
package com.lp.DAO; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.lp.bean.city; import com.lp.bean.goods; import com.sun.org.apache.bcel.internal.generic.GETSTATIC; /** * 2015.7.20 利用java反射机制实现万能DAO 即使bean层的实体类字段改变 也能实现增删查改 * * @author liupeng */ public class DaoPro { // 由数据库名称得到数据库中的所有列 public List<String> getColumns(String tableName) { Connection connection = DbHelper.getCon(); Statement statement = DbHelper.getStatement(); ResultSet resultSet = null; List<String> list = new ArrayList<String>(); try { String sql = "select * from " + tableName + " where 1=2"; resultSet = DbHelper.getStatement().executeQuery(sql); ResultSetMetaData data = resultSet.getMetaData(); int columnsCount = data.getColumnCount(); for (int i = 1; i <= columnsCount; i++) { String s = data.getColumnName(i); list.add(s); } } catch (SQLException e) { e.printStackTrace(); } finally { DbHelper.cloRes(connection, statement, resultSet); } return list; } // 得到数据库中的所有数据 public List getList(Class cl) { int i = 0; List objs = new ArrayList(); Connection connection = DbHelper.getCon(); Statement statement = DbHelper.getStatement(); ResultSet resultSet = null; Field[] fields = cl.getDeclaredFields(); List<String> columnsName = getColumns(cl.getSimpleName()); String sql = "select * from " + cl.getSimpleName(); try { System.out.println(sql); resultSet = statement.executeQuery(sql); System.out.println(i++); while (resultSet.next()) { System.out.println(i++); Object obj = cl.newInstance(); for (String str : columnsName) { for (Field ff : fields) { if (str.equals(ff.getName())) { ff.setAccessible(true); ff.set(obj, resultSet.getObject(ff.getName())); break; } } } objs.add(obj); } } catch (SQLException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } return objs; } // 添加数据返回主键的方法 public int addData(Object object) { int id = 0; Connection connection = DbHelper.getCon(); ResultSet resultSet = null; PreparedStatement preparedStatement = null; String tableName = object.getClass().getSimpleName(); Field[] fields = object.getClass().getDeclaredFields(); List<String> allColumns = getColumns(tableName); StringBuffer buffer = new StringBuffer(); StringBuffer buffer1 = new StringBuffer(); buffer.append("insert into "); buffer.append(tableName); buffer.append(" ("); for (int i = 1; i < allColumns.size(); i++) { buffer.append(allColumns.get(i)); buffer1.append("?"); if (i != allColumns.size() - 1) { buffer.append(","); buffer1.append(","); } } buffer.append(") values ("); buffer.append(buffer1); buffer.append(")"); // System.out.println(buffer.toString()); try { preparedStatement = connection.prepareStatement(buffer.toString()); for (int i = 1; i < allColumns.size(); i++) { for (int j = 0; j < fields.length; j++) { if ((fields[j].getName()).equals(allColumns.get(i))) { fields[j].setAccessible(true); if (fields[j].get(object) == null) { preparedStatement.setObject(i, "此字段无填充"); } else { preparedStatement.setObject(i, fields[j].get(object)); } break; } } } int a = preparedStatement.executeUpdate(); if (a > 0) { resultSet = preparedStatement.getGeneratedKeys(); if (resultSet.next()) { id = resultSet.getInt(1); } } } catch (SQLException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } finally { DbHelper.cloRes(connection, preparedStatement, resultSet); } return id; } // 根据实体类实现一个或者多个条件查询 public List getByBean(Object object) { List some = new ArrayList(); Connection connection = DbHelper.getCon(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { // 得到实体类不为空的属性和属性值 List<String> listVal = new ArrayList<String>(); List<String> listField = new ArrayList<String>(); Field[] fields = object.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { fields[i].setAccessible(true); // 把id字段除去,知道id就不用查了 if (fields[i].get(object) != null && !(fields[i].get(object) instanceof Integer)) { listVal.add((String) fields[i].get(object)); listField.add(fields[i].getName()); } } // 拼接sql语句 StringBuffer buffer = new StringBuffer(); buffer.append("select "); buffer.append("*"); buffer.append(" from "); buffer.append(object.getClass().getSimpleName()); buffer.append(" where "); for (int i = 0; i < listField.size(); i++) { buffer.append(listField.get(i)); buffer.append("="); buffer.append("‘" + listVal.get(i) + "‘"); if (i != listField.size() - 1) { buffer.append(" and "); } } System.out.println(buffer.toString()); // 执行查询 preparedStatement = connection.prepareStatement(buffer.toString()); resultSet = preparedStatement.executeQuery(); int count = resultSet.getMetaData().getColumnCount(); while (resultSet.next()) { Object ob = object.getClass().newInstance(); //获取不含id的列 List<String> list = getColumns(object.getClass() .getSimpleName()); list.add("id"); Field[] fields2 = object.getClass().getDeclaredFields(); for (int j = 0; j < fields2.length; j++) { fields2[j].setAccessible(true); for (int i = 1; i <= list.size()-1; i++) { if (list.get(i).equals(fields2[j].getName())) { fields2[j].set(ob, resultSet.getObject(list.get(i))); } } } some.add(ob); } } catch (SQLException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } finally { DbHelper.cloRes(connection, preparedStatement, resultSet); } return some; } // 更新数据,由实体类封装的id,得到主键,实现更新 public boolean updateBean(Object object) { int id = 0; int a = 0; Connection connection = DbHelper.getCon(); Statement statement = null; ResultSet resultSet = null; Field[] fields = object.getClass().getDeclaredFields(); // 得到id的值,确定要更新那一条数据 try { for (int i = 0; i < fields.length; i++) { fields[i].setAccessible(true); if (fields[i].getName().equals("id")) { if ((Integer) fields[i].get(object) != 0) { id = (Integer) fields[i].get(object); } else { return false; } } } // 拼接 sql 语句 StringBuffer buffer = new StringBuffer(); buffer.append("update "); buffer.append(object.getClass().getSimpleName()); buffer.append(" set "); List<String> list = getColumns(object.getClass().getSimpleName()); list.remove("id"); for (int i = 0; i < list.size(); i++) { for (int j = 0; j < fields.length; j++) { if (fields[j].getName().equals(list.get(i))) { if (fields[j].get(object) != null) { buffer.append(list.get(i)); buffer.append("="); buffer.append("‘" + fields[j].get(object) + "‘,"); } } } } buffer.delete(buffer.length() - 1, buffer.length()); buffer.append(" where id="); buffer.append(id); System.out.println(buffer.toString()); statement = connection.createStatement(); a = statement.executeUpdate(buffer.toString()); System.out.println(a); } catch (Exception e) { e.printStackTrace(); } finally { DbHelper.cloRes(connection, statement, resultSet); } if (a > 0) { return true; } return false; } public static void main(String[] args) { goods c = new goods(); c.setGoodDetail("我的更改"); goods good = (goods) new DaoPro().getByBean(c).get(0); System.out.println(good.getId()); } }
时间: 2024-10-15 10:15:22