Implementation via generics + reflection

// Generic query for different tables: return an object (version 1.0)
	public <T> T getInstance(Class<T> clazz, String sql, Object... args) {

		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			// 1. Obtain the database connection
			conn = JDBCUtils.getConnection();

			// 2. Precompile SQL statements to obtain the PreparedStatement object
			ps = conn.prepareStatement(sql);

			// 3. Populate placeholders
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}

			// 4. Execute executeQuery() to obtain the ResultSet
			rs = ps.executeQuery();

			ResultSetMetaData = ResultSetMetaData
			ResultSetMetaData rsmd = rs.getMetaData();

			// 6.1 Using ResultSetMetaData to obtain columnCount,columnLabel; Obtain column values from a ResultSet
			int columnCount = rsmd.getColumnCount();
			if (rs.next()) {
				T t = clazz.newInstance();
				for (int i = 0; i < columnCount; i++) {// Iterate over each column

					// Get column values
					Object columnVal = rs.getObject(i + 1);
					// Get the column alias: the column alias, used as the class attribute name
					String columnLabel = rsmd.getColumnLabel(i + 1);
					// 6.2 Use reflection to assign values to corresponding properties of objects
					Field field = clazz.getDeclaredField(columnLabel);
					field.setAccessible(true);
					field.set(t, columnVal);

				}

				returnt; }}catch (Exception e) {

			e.printStackTrace();
		} finally {
			// 7. Close resources
			JDBCUtils.closeResource(conn, ps, rs);
		}

		return null;

	}
Copy the code