![](/img/trans.png)
[英]How do I write nested AND and OR blocks in a hibernate criteria with grails createCriteria
[英]How do I write a createCriteria in grails which pull only few columns from the table instead of all columns?
如何在grails中编写createCriteria,将其从表中仅拉出几列而不是所有列?
我有一个称为广告的表格。 我只想检索“标题”,“价格”和“照片”列。
def c = Classified.createCriteria()
def records = c.list {
eq('publish_date', '2014-06-06')
}
maxResults(8)
}
上面的查询检索所有记录。 如何限制为仅几列?
尝试这个:
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)
}
现在, records
将是地图列表而不是列表列表,您可以通过别名访问records[n].ttl
属性records[n].ttl
, records[n].cost
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.