gorm投影和元信息的丧失



在使用属性上的投影时,结果将作为列表返回,其元素与投影块中定义的序列相同。同时,列表中丢失了属性名称,这对于开发人员来说确实不利,因为结果将传递,呼叫者需要知道什么值属于哪个属性。有没有办法从标准查询中返回以属性名称作为值的关键的地图?

所以,以下代码:

def c = Trade.createCriteria()
def remicTrades = c.list {
    projections {
        property('title', 'title')
        property('author.name', 'author')
    }
    def now = new Date()
    between('publishedDate', now-365, now)
}

此返回:

[['book1', 'author1']['book2', 'author2']]

相反,我希望它返回:

[[book:'book1', author:'author1'][book:'book2', author:'author2']]

我知道我可以在获得结果后以这种方式安排,但是我认真地认为,标准应该使用该财产别名返回模拟SQL查询结果的地图列表,而不是平淡的<<<<<<<<<<<。/p>

重复:带有标准的Grails查询:如何用列返回地图?
以及相应的答案(和解决方案):https://stackoverflow.com/a/16409512/1263227

使用ResultTransFormer。

import org.hibernate.criterion.CriteriaSpecification
Trade.withCriteria {
  resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
  projections {
    property('title', 'title')
    property('author.name', 'author')
  }
  def now = new Date()
  between('publishedDate', now-365, now)
}     

同意您的问题推理,这确实应该是核心Gorm解决方案的一部分。也就是说,这是我的解决方法;

def props = ['name','phone']
def query = Person.where {}.projections {
        props.each{
                property(it)
        }
}
def people = query.list().collect{ row->
        def cols = [:]
        row.eachWithIndex{colVal, ind->
            cols[props[ind]] = colVal
        }
        cols
}
println people // shows [['name':'John','phone':'5551212'],['name':'Magdalena','phone':'5552423']]

最新更新