Search code examples
sqlhibernategrailsgrails-orm

Include column names in Grails SQL query results


I have a query that looks like this...

        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()

The problem is the .list method returns an array that has no column names. Does anybody know of a way to include/add the column names from a Grails native sql query. I could obviously transform the results into a map and hard code the column names myself.


Solution

  • Use setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP) for the query. This would result a map of entries.

    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}
    

    I tested it and realized that earlier I used to use the column number to fetch each field instead of the column name.

    NOTE
    Keys are upper case. so ex_source would be EX_SOURCE in the result map.