![](/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.