/**
* 使用反射动态的实现对不同表的通用查询
* @author baihang
* @create 2022-03-04 17:43
*/
public class CommonQuery {
@Test
public void test() {
String sql = "select id stuId, name stuName from student where id = ?;";
Student queryInstance = getQueryInstance(Student.class, sql, 1002);
System.out.println(queryInstance);
String sql1 = "select teamID, teamName, location, arena from teams where teamID = ?;";
Teams queryInstance1 = getQueryInstance(Teams.class, sql1, 1);
System.out.println(queryInstance1);
}
public <T> T getQueryInstance(Class<T> clazz, String sql, Object...args) {
Connection connection = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
connection = JDBCUtils.getConnection();
ps = connection.prepareStatement(sql);
for(int i = 0; i < args.length; i++) {
//对sql语句设置占位符
ps.setObject(i + 1, args[i]);
}
//获取结果集
resultSet = ps.executeQuery();
//获取结果集的元数据(数据的描述)
ResultSetMetaData rsmd = resultSet.getMetaData();
//获取结果集列数
int columnCount = rsmd.getColumnCount();
if(resultSet.next()) {
T t = clazz.newInstance();//使用反射动态获取类(表)的对象
for(int i = 0; i < columnCount; i++) {
//获取每个列的值
Object objectValue = resultSet.getObject(i + 1);
//获取结果集每个列的别名 ---> 对应Java类属性名
//String columnLabel = rsmd.getColumnName(i + 1); //不靠谱,不推荐使用!!!
String columnLabel = rsmd.getColumnLabel(i + 1); //推荐使用!!!
//利用反射获取列名columnName对应的属性
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
//将t对象对应的属性赋值为objectValue
field.set(t, objectValue);
}
return t;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtils.closeResource(connection, ps, resultSet);
}
return null;
}
}
?二、teams表(类)
public class Teams {
private int teamID;
private String teamName;
private String location;
private String arena;
public Teams() {
}
public Teams(int teamID, String teamName, String location, String arena) {
this.teamID = teamID;
this.teamName = teamName;
this.location = location;
this.arena = arena;
}
@Override
public String toString() {
return "Teams{" +
"teamID=" + teamID +
", teamName='" + teamName + '\'' +
", location='" + location + '\'' +
", arena='" + arena + '\'' +
'}';
}
public int getTeamID() {
return teamID;
}
public void setTeamID(int teamID) {
this.teamID = teamID;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getArena() {
return arena;
}
public void setArena(String arena) {
this.arena = arena;
}
}
|