You need to enable JavaScript to run this app. 如何将BigQuery的TableResult转为List<Map<String,Any>>并实现JdbcTemplate式rowMapper功能
优惠活动
大模型
产品
解决方案
定价
更多

如何将BigQuery的TableResult转为List<Map<String,Any>>并实现JdbcTemplate式rowMapper功能

问题解答

1. 类型转换报错原因及List<Map<String, Any>>转换实现

com.google.cloud.bigquery.TableResult是BigQuery客户端封装的独立查询结果类,未实现java.util.List接口,直接强制类型转换不符合Java/Kotlin的类型继承规则,因此抛出类型转换异常。
正确转换代码如下(Kotlin版本):

val queryConfig = QueryJobConfiguration.newBuilder(modSql)
    .setUseLegacySql(false)
    .build()
val queryJob = bigQuery.create(JobInfo.newBuilder(queryConfig).build())
val result = queryJob.getQueryResults()
// 先获取查询结果的所有列名
val fieldNames = result.schema?.fields?.map { it.name } ?: emptyList()
// 遍历每一行组装Map,最终转为List
val resultList = result.map { row ->
    fieldNames.associateWith { fieldName ->
        row.get(fieldName).value
    }
}
return resultList

2. 类似JdbcTemplate的RowMapper能力实现

可以通过封装通用查询高阶函数实现该能力,将行映射逻辑作为参数传入,使用方式和JdbcTemplate完全一致:

通用封装代码

/**
 * 类似JdbcTemplate的通用BigQuery查询方法
 * @param sql 查询SQL
 * @param rowMapper 行映射函数,传入单行结果FieldValueList,返回映射后的自定义类型对象
 * @return 映射后的结果列表
 */
fun <T> bigQuery.query(sql: String, rowMapper: (FieldValueList) -> T): List<T> {
    val queryConfig = QueryJobConfiguration.newBuilder(sql)
        .setUseLegacySql(false)
        .build()
    val queryJob = this.create(JobInfo.newBuilder(queryConfig).build())
    val result = queryJob.getQueryResults()
    // 遍历每一行调用rowMapper转换,收集为列表返回
    return result.map { row -> rowMapper(row) }
}

使用示例

// 示例1:映射为List<Map<String, Any>>,和你最初的需求一致
val mapResult = bigQuery.query(modSql) { row ->
    row.schema.fields.map { it.name }.associateWith { fieldName ->
        row.get(fieldName).value
    }
}

// 示例2:映射为自定义实体类列表,和JdbcTemplate的RowMapper用法完全一致
data class User(
    val id: Long,
    val name: String,
    val age: Int
)
val userResult = bigQuery.query("select id,name,age from user") { row ->
    User(
        id = row.get("id").longValue,
        name = row.get("name").stringValue,
        age = row.get("age").intValue
    )
}

内容的提问来源于stack exchange,提问作者David Wallace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 21:42:01