如何在grails中编写一个createCriteria,它只从表中拉出几列而不是所有列?

Mub*_*oul 1 grails hql grails-orm

如何在grails中编写一个createCriteria,它只从表中拉出几列而不是所有列?

我有一张叫做广告的桌子.我想只检索列"标题","价格"和"照片".

def c = Classified.createCriteria()
    def records = c.list {
            eq('publish_date', '2014-06-06')
        }
        maxResults(8)
    }
Run Code Online (Sandbox Code Playgroud)

上面的查询检索所有记录.如何限制只有几列?

Dón*_*nal 5

试试这个:

def records = Classified.withCriteria {
    eq('publish_date', '2014-06-06')

    projections {
        property('title')
        property('price')
        property('photo')
    }        
    maxResults(8)
}
Run Code Online (Sandbox Code Playgroud)


Ian*_*rts 5

您可以使用投影来实现这一目标 - 最简单的方法

projections {
    property('title')
    property('price')
    property('photo')
}
Run Code Online (Sandbox Code Playgroud)

会导致c.list返回三元素列表的列表,其中records[n][0]是标题,records[n][1]价格等.如果您希望能够通过名称而不是数字访问属性,那么您需要分配别名并使用结果转换器

import org.hibernate.transform.AliasToEntityMapResultTransformer

def c = Classified.createCriteria()
def records = c.list {
    eq('publish_date', '2014-06-06')
    maxResults(8)
    projections {
        // first param is the property name, second is the alias definition -
        // typically you'd leave them the same but here I make them different
        // for demonstration purposes
        property('title', 'ttl')
        property('price', 'cost')
        property('photo', 'picture')
    }
    resultTransformer(AliasToEntityMapResultTransformer.INSTANCE)
}
Run Code Online (Sandbox Code Playgroud)

现在,records必应地图,而不是一个列表的列表清单,您可以通过别名访问的规划特性- records[n].ttl,records[n].cost等等.