我有一个看起来像这样的查询......
def data = session.createSQLQuery("""SELECT
a.id AS media_id,
a.uuid,
a.date_created,
a.last_updated,
a.device_date_time,
a.ex_time,
a.ex_source,
a.sequence,
a.time_zone,
a.time_zone_offset,
a.media_type,
a.size_in_bytes,
a.orientation,
a.width,
a.height,
a.duration,
b.id AS app_user_record_id,
b.app_user_identifier,
b.application_id,
b.date_created AS app_user_record_date_created,
b.last_updated AS app_user_record_last_updated,
b.instance_id,
b.user_uuid
FROM media a, app_user_record b
WHERE a.uuid = b.user_uuid
LIMIT :firstResult, :maxResults """)
.setInteger("firstResult", cmd.firstResult)
.setInteger("maxResults", cmd.maxResults)
.list()
问题是 .list 方法返回一个没有列名的数组。有谁知道从 Grails native sql 查询中包含/添加列名的方法。我显然可以将结果转换为 map 并自己对列名进行硬编码。
最佳答案
使用setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP)
用于查询。这将产生条目映射。
import org.hibernate.Criteria
def query = """Your query"""
def data = session.createSQLQuery(query)
.setInteger("firstResult", cmd.firstResult)
.setInteger("maxResults", cmd.maxResults)
.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP)
.list()
data.each{println it.UUID}
我对其进行了测试,并意识到之前我曾经使用列号而不是列名来获取每个字段。
注意
键是大写的。所以
ex_source
将是 EX_SOURCE
在结果图中。
关于sql - 在 Grails SQL 查询结果中包含列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18839059/