反射实现增删改查(DAO层)——查询数据
Posted 云中志
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了反射实现增删改查(DAO层)——查询数据相关的知识,希望对你有一定的参考价值。
先贴出代码,后续补充自己的思路、配置文件、使用方式:
/**
*
* 数据查询
*
*/
@Override
public List<?> queryObject(List<Map<String, Object>> params,
String tableName) {
List<Object> objectList = new ArrayList<Object>();
StringBuilder sql = new StringBuilder("SELECT * FROM " + tableName
+ " WHERE 1=1");
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBConnection.getConnection();
if (params != null && params.size() > 0) {
for (int i = 0; i < params.size(); i++) {
Map<String, Object> map = params.get(i);
sql.append(" AND " + map.get("name") + " "
+ map.get("rela") + " " + map.get("value") + " ");
}
}
preparedStatement = connection.prepareStatement(sql.toString());
resultSet = preparedStatement.executeQuery();
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
// 获取数据列数
int columnsCount = resultSetMetaData.getColumnCount();
Field field = null;
Object object = null;
while (resultSet.next()) {
/**
* 获取实例化对象
*/
object = objectClass.newInstance();
String columnName = null;
String columnTypeName = null;
String columnValue = null;
for (int i = 1; i <= columnsCount; i++) {
columnName = resultSetMetaData.getColumnName(i);
columnTypeName = resultSetMetaData.getColumnTypeName(i);
columnValue = resultSet.getString(i);
field = object.getClass().getDeclaredField(columnName);
field.setAccessible(true);
switch (columnTypeName) {
case "INT":
field.set(object, Integer.parseInt(columnValue));
break;
case "VARCHAR":
field.set(object, columnValue);
break;
case "FLOAT":
field.set(object, Float.parseFloat(columnValue));
break;
case "Date":
field.set(object,
new SimpleDateFormat().parse(columnValue));
break;
}
}
objectList.add(object);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} finally {
DBConnection.close(connection, preparedStatement, resultSet);
}
return objectList;
}
以上是关于反射实现增删改查(DAO层)——查询数据的主要内容,如果未能解决你的问题,请参考以下文章