如何在grails中编写一个createCriteria,它只从表中提取很少的列,而不是所有的列?
如何在grails中编写一个createCriteria,它只从表中提取很少的列,而不是所有的列 我有一个名为Ads的表。我只想检索“标题”、“价格”和“照片”列 上面的查询检索所有记录。如何仅限制为几个列?尝试以下方法:如何在grails中编写一个createCriteria,它只从表中提取很少的列,而不是所有的列?,grails,hql,gorm,Grails,Hql,Gorm,如何在grails中编写一个createCriteria,它只从表中提取很少的列,而不是所有的列 我有一个名为Ads的表。我只想检索“标题”、“价格”和“照片”列 上面的查询检索所有记录。如何仅限制为几个列?尝试以下方法: def records = Classified.withCriteria { eq('publish_date', '2014-06-06') projections { property('title') property
def records = Classified.withCriteria {
eq('publish_date', '2014-06-06')
projections {
property('title')
property('price')
property('photo')
}
maxResults(8)
}
您可以使用投影来实现这一点-最简单
projections {
property('title')
property('price')
property('photo')
}
将导致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)
}
现在,
记录
将是一个地图列表,而不是列表列表,您可以通过别名-记录[n]。ttl
,记录[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)
}