最近想熟悉jdbc编程和反射机制,于是产生了下面的代码,其中返回集合的接口绝对测试通过,返回对象的没有测试,应该也没有问题,如果有发现问题的小伙伴,帮忙指出下,谢谢!
当然后续我自己也会再来测一下,这次先记录下来。
package com.jfqqqq.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class JDBCTemplate {
private Logger logger = LoggerFactory.getLogger(JDBCTemplate.class);
public List queryObjectList(Connection connection, String sql, Class requiredClass) throws Exception {
List resutls = new ArrayList<>();
business(connection, sql, requiredClass, resutls, false);
return resutls;
}
public <T> T queryObject(Connection connection, String sql, Class<T> requiredClass) throws Exception {
T instance = requiredClass.getDeclaredConstructor().newInstance();
business(connection, sql, requiredClass, instance, true);
return instance;
}
private <T> T business(Connection connection, String selectSqlTmp, Class<T> requiredClass, Object object, boolean isSingle) {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement(selectSqlTmp);
resultSet = preparedStatement.executeQuery();
if (isSingle) {
while (resultSet.next()) {
T instance = generateObjects(resultSet, requiredClass);
object = (T) instance;
}
// else {
// logger.info("没有查询结果!");
// }
// generateObjects(resultSet, requiredClass, null);
} else {
List<T> results = (List<T>) object;
while (resultSet.next()) {
T instance = generateObjects(resultSet, requiredClass);
results.add(instance);
}
// else {
// logger.info("没有查询结果!");
// }
}
} catch (Exception e) {
logger.error("查询数据库出错!", e);
} finally {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException throwables) {
logger.error("preparedStatement error:", throwables);
}
}
return null;
}
private <T> T generateObjects(ResultSet resultSet, Class<T> requiredClass) throws Exception {
T instance = requiredClass.getDeclaredConstructor().newInstance();
Field[] declaredFields = requiredClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
String fieldName = declaredField.getName();
Class<?> type = declaredField.getType();
declaredField.set(instance, getFieldValue(resultSet, fieldName, type));
}
return instance;
}
private <A> A getFieldValue(ResultSet resultSet, String fieldName, Class<A> fieldclazz) throws Exception {
A object = null;
try {
if (isExitColumn(resultSet, fieldName)) {
object = (A) resultSet.getObject(fieldName, fieldclazz);
}
} catch (Exception e) {
logger.error("{}", e);
}
return object;
}
private boolean isExitColumn(ResultSet resultSet, String fieldName) {
try {
resultSet.findColumn(fieldName);
return true;
} catch (SQLException throwables) {
return false;
}
}
}