What is their difference and why and where we need to use them,i think it seems like they have no difference at all to me ?
withCriteria { ... } is essentially shorthand for createCriteria().list { ... }. If you need to use any of the other criteria methods (get, count, ...) or pass pagination parameters to list then you have to use the long-hand form.
SomeDomain.createCriteria().list(max:10, offset:50) {
// ...
}
It's worth adding what I just came across in the grails documentation for createCriteria().
Because that query includes pagination parameters (max and offset), this will return a PagedResultList which has a getTotalCount() method to return the total number of matching records for pagination. Two queries are still run, but they are run for you and the results and total count are combined in the PagedResultList.
Source
This means you can use getTotalCount() without having to initiate the call (it's made for you). This is very helpful. The example documentation shows:
def c = Account.createCriteria()
def results = c.list (max: 10, offset: 10) {
like("holderFirstName", "Fred%")
and {
between("balance", 500, 1000)
eq("branch", "London")
}
order("holderLastName", "desc")
}
println "Rendering ${results.size()} Accounts of ${results.totalCount}"
This capability is not available when using withCriteria().
Example of createCriteria():
def criteria = OfferCredit.createCriteria {
offer {
eq('status', LeverageUtils.ACTIVE_STATUS)
ge('expirationDate', new Date())
}
user {
eq('userId', userId)
}
eq('status', LeverageUtils.ACTIVE_STATUS)
order('creationDate', 'asc')
}
criteria.list()
Example of withCriteria():
List<Supermarket> results = Supermarket.withCriteria {
like("sp_street", params.street)
productSupermarket {
product {
idEq(params.product)
}
// or just eq('product', someProduct)
}
maxResults(10)
}
withCriteria executes and returns the list. It provides a closure using which you can customize the criteria before it gets executed.
createCriteria just creates a criteria object which you can modify and then explicitly call the list method to execute.
If criteria is simple or if it is defined in a single place it is better to use withCriteria.
If you need to pass the criteria around (create it in one function and pass it to others) createCriteria would be better. I think withCriteria support is limited.
withCriteria ->
Purpose -> Allows inline execution of Criteria queries.
If no matching records are found, an empty List is returned.
If a projection is specified:
returns a single value if it only contains one field
a List in case there are multiple fields in the projection
Related
I have a domain class
class Url {
UUID id
String url
static hasMany = [
indications:UrlIndication
]
...
}
And
class UrlIndication {
UUID id
String name
static belongsTo = Url
...
}
I want to choose urls so that it has all the necessary UrlIndication elements in a given list indicationsId.
For that I use an association and criteria like this one:
indications {
and {
indicationsId.each{
indication->
eq ('id',UUID.fromString(indication as String))
}
}
}
However, all I got is an empty result. Can you suggest any modifications/ other methods so that I can do this? Thanks in advance
Your query returned an empty list because it's the equivalent of the expression (pseudo-code): if 1 = 1 and 1 = 2 and 1 = 3
Such an expression would always be false. in or inList would not work for the reason #innovatism described.
In theory, Criteria's eqAll() or HQL's = ALL would work. But, I don't know for sure because I could not get either one to work.
What will work is to use inList to return a subset of Urls: those which contain at least one of the UrlIndication IDs. Then use Groovy's containsAll() to finish the job.
def ids = indicationsId.collect { UUID.fromString(it as String) }
Url.createCriteria()
.buildCriteria {
indications {
inList 'id', ids
}
}
.setResultTransformer(org.hibernate.Criteria.DISTINCT_ROOT_ENTITY)
.list()
.findAll {
it.indications.id.containsAll(ids)
}
Since the query has the potential to return duplicate Url instances, the ResultTransformer is set to return a unique list.
Finally, findAll() is used along with containsAll() to filter the list further.
Using eqAll (maybe)
Something like the following might work. Something funky is going on with Grails' HibernateCriteriaBuilder that causes the eqAll method to look up properties in the root entity; completely ignoring the sub criteria. So the following uses Hibernate directly. It didn't work for me, but it's as close as I could get. And it gave me a head-ache!
Url.createCriteria().buildCriteria {}
.createCriteria('indications', 'i')
.add(org.hibernate.criterion.Property.forName('i.id').eqAll(org.hibernate.criterion.DetachedCriteria.forClass(UrlIndication)
.add(org.hibernate.criterion.Restrictions.in('id', ids))
.setProjection(org.hibernate.criterion.Property.forName('id'))
))
.setResultTransformer(org.hibernate.Criteria.DISTINCT_ROOT_ENTITY)
.list()
The problem I had is I could not get Restrictions.in to work. Restrictions.eq works fine.
the in clause should do:
indications {
'in' 'id', indicationsId.collect{ UUID.fromString indication.toString() }
}
I have a create criteria using multiple params with pagination.
The issue that I´m having that if is possible to re-use the code inside the and for others create-criteria totally differents, witouth having to duplicate the code.
I reffer that if I have the cases createcriteria and want to do the same "filters" on the cases2 not have to duplicate the code, unify both createCriteria is not an option
Per example, the problem that I´m facing is that one needs to be with pagination, and other don´t need to be, and both needs to access distinct fields, so the unique option is to create two identical create criteria if I´m not missing something.
That is a example, that cases is at least 90% indetically to cases2, and what would be a good mode to reuse the code?
def cases = PpCase.createCriteria().list{
and{
if(limit){
maxResults(limit)
}
firstResult(offset)
order("mostRecentPaymentDate", "desc")
order("totalAmount", "desc")
if(params.admin_id){
eq("adminId",params.admin_id)
}
if(params.status){
eq("status",params.status.toUpperCase() as PpCase.Status)
}
if(params.date_from){
ge('dateCreated', Date.parse("yyyy-MM-dd",params.date_from))
}
if(params.date_to){
le('dateCreated', Date.parse("yyyy-MM-dd",params.date_to))
}
if(params.date_closed_from){
ge('closedDate', Date.parse("yyyy-MM-dd",params.date_closed_from))
}
if(params.date_closed_to){
le('closedDate', Date.parse("yyyy-MM-dd",params.date_closed_to))
}
}
}
def cases2 = PpCase.createCriteria().list{
and{
firstResult(offset)
order("mostRecentPaymentDate", "desc")
order("totalAmount", "desc")
if(params.admin_id){
eq("adminId",params.admin_id)
}
if(params.status){
eq("status",params.status.toUpperCase() as PpCase.Status)
}
if(params.date_from){
ge('dateCreated', Date.parse("yyyy-MM-dd",params.date_from))
}
if(params.date_to){
le('dateCreated', Date.parse("yyyy-MM-dd",params.date_to))
}
if(params.date_closed_from){
ge('closedDate', Date.parse("yyyy-MM-dd",params.date_closed_from))
}
if(params.date_closed_to){
le('closedDate', Date.parse("yyyy-MM-dd",params.date_closed_to))
}
}
}
More real example:
In cases I need some fields, but with a limit , and in cases2 I need distinct fields, and witouth a limit,I´m duplicating the 90% of the code.
def cases = PpCase.createCriteria().list{
projections {
sum("field1")
countDistinct("id")
}
and{
if(limit){
maxResults(limit)
}
//HERE SHOULD BE THE CODE THAT I NEED TO REUTILIZE
}
def cases2 = PpCase.createCriteria().list{
projections {
sum("field2")
countDistinct("id")
}
and{
//HERE SHOULD BE THE CODE THAT I NEED TO REUTILIZE
}
I'd use "where" queries, which use DetachedCriteria under the hood, or DetachedCriteria directly. where queries don't run until you call list/get/count/exists/deleteAll/updateAll, so they're great candidates for composing queries in parts. Named queries can similarly be composed, but they need to be complete, runnable queries, but a partial where query is fine as long as you add the missing parts via composition before running them. They're also more flexible since you can use them to delete and update.
I'm not sure what you mean when you say "unify both createCriteria is not an option", especially considering in the code above you are executing the exact same query twice and ending up with two lists containing the same rows.
One way to reuse your criteria is to just define the criteria as a seperate closure, and pass that to createCriteria.
Closure fetchPayments = {
and{
if(limit){
maxResults(limit)
}
firstResult(offset)
order("mostRecentPaymentDate", "desc")
order("totalAmount", "desc")
if(params.admin_id){
eq("adminId",params.admin_id)
}
if(params.status){
eq("status",params.status.toUpperCase() as PpCase.Status)
}
if(params.date_from){
ge('dateCreated', Date.parse("yyyy-MM-dd",params.date_from))
}
if(params.date_to){
le('dateCreated', Date.parse("yyyy-MM-dd",params.date_to))
}
if(params.date_closed_from){
ge('closedDate', Date.parse("yyyy-MM-dd",params.date_closed_from))
}
if(params.date_closed_to){
le('closedDate', Date.parse("yyyy-MM-dd",params.date_closed_to))
}
}
}
def cases = PpCase.createCriteria().list(fetchPayments)
def cases2 = PpCase.createCriteria().list(fetchPayments)
You can do this by using named query :
have look to documentation .namedQueries
I am working on a grails application, in this I have to apply filter box on list.gsp. When I am filtering using following query(in my service) I am getting paginated list :
def clientCriteria = TripOrder.createCriteria()
def searchResults = clientCriteria.list(max: params.max, offset: params.offset, sort: params.sort, order: params.order){
ilike("origin", "${searchFor}%")
}
println searchResults.getTotalCount()
[searchResults: searchResults, searchResultSize: searchResults.getTotalCount()]
But my problem is that when I am using findAll, I am not able to get paginated list, query as follows :
def searchResults = TripOrder.findAll("from TripOrder as t where t.status.status=:status", [status: searchFor], [max: maximum, sort: params.sort, order: params.order])
println searchResults.size()
[searchResults: searchResults, searchResultSize: searchResults.size()]
Note : Because of some reasons I have to use findAll() HQL instead criteria queries.
Above result provide only number of list equal to max instead of provide paginated list.
Please provide me solution for getting paginated list using findAll().
Thanks.
Based on your comment, you can do like this where you get a PagedResultList
def results = TripOrder.createCriteria.list(params) {
customer {
ilike 'firstName', "%$searchFor%"
}
}
assert results.size() != results.totalCount
It basically fires another query for the totalCount, if you want to stick to findAll or something like findAll instead of criteria then you can imbibe a better alternative by using a DetachedCriteria/where query which lazily executes the query on demand. Again, you won't be able to get the total count in first query. You have to fire another for the same.
def query = TripOrder.where {
customer.firstName =~ searchFor
}
//Query executed only when list() is called
def results = query.list( params )
//Only executed when count() is called
def totalCount = query.count()
findAll isn't designed to return a paginated list. It returns an array. This is clearly stated in the documentation.
I have two very similar methods in Grails, something like "calculate statistics by os" and "calculate statistics by browser" - effectively both prepare some things, then run a similar query on the DB, then do things with the results. The only part where the methods differ is the query they run in the middle of my method -
def summary = c.list {
eq('browser', Browser.get(1)) // OR eq('os', OS.get(1))
between('date', dates.start, dates.end)
}
It occurred to me that the ideal way to refactor it would be to pass in the first line of the closure as a method parameter. Like
doStats (Closure query) {
...
def summary = c.list {
query
between('date', dates.start, dates.end)
}
}
I tried this but "query" gets ignored. I tried query() instead but then the query clause is executed where defined, so this doesn't work either. I suppose I could just pass the whole closure as a parameter but that seems wrong - the query might also get more complicated in future.
Anyone have any better ideas?
I found leftShift operator useful for composing closure from two separate ones. What you can do is:
Closure a = { /*...*/ }
Closure b = { /*...*/ }
Closure c = a << b
Take a look at this example:
def criteria = {
projection Projections.distinct(Projections.property('id'))
and {
eq 'owner.id', userDetails.id
if (filter.groupId) {
eq 'group.id', filter.groupId
}
}
}
List<Long> ids = Contact.createCriteria().list(criteria << {
maxResults filter.max
firstResult filter.offset
})
Integer totalCount = Contact.createCriteria().count(criteria)
What you can see here is that I'm creating a criteria for listing ant counting GORM objects. Criterias for both cases are almost the same, but for listing purposes I also need to include limit and offset from command object.
You're using the criteria DSL which might be different than plain groovy closures.
To do what you're asking, you can use the method described here -
http://mrhaki.blogspot.com/2010/06/grails-goodness-refactoring-criteria.html
and put your query in to private method.
The more elegant solution for this is to use named queries in grails -
http://grails.org/doc/latest/ref/Domain%20Classes/namedQueries.html
Look at the
recentPublicationsWithBookInTitle {
// calls to other named queries…
recentPublications()
publicationsWithBookInTitle()
}
example -
Not sure about with the Grails Criteria builder, but with other builders, you can do something like:
doStats (Closure query) {
def summary = c.list {
query( it )
between('date', dates.start, dates.end)
}
}
And call this via:
def f = { criteria ->
criteria.eq( 'browser', Browser.get( 1 ) )
}
doStats( f )
If not, you're probably best looking at named queries like tomas says
I am using Nimble and Shiro for my security frameworks and I've just come accross a GORM bug. Indeed :
User.createCriteria().list {
maxResults 10
}
returns 10 users whereas User.list(max: 10) returns 9 users !
After further investigations, I found out that createCriteria returns twice the same user (admin) because admin has 2 roles!!! (I am not joking).
It appears that any user with more than 1 role will be returned twice in the createCriteria call and User.list will return max-1 instances (i.e 9 users instead of 10 users)
What workaround can I use in order to have 10 unique users returned ?
This is a very annoying because I have no way to use pagination correctly.
My domain classes are:
class UserBase {
String username
static belongsTo = [Role, Group]
static hasMany = [roles: Role, groups: Group]
static fetchMode = [roles: 'eager', groups: 'eager']
static mapping = {
roles cache: true,
cascade: 'none',
cache usage: 'read-write', include: 'all'
}
}
class User extends UserBase {
static mapping = {cache: 'read-write'}
}
class Role {
static hasMany = [users: UserBase, groups: Group]
static belongsTo = [Group]
static mapping = { cache usage: 'read-write', include: 'all'
users cache: true
groups cache: true
}
}
Less concise and clear, but using an HQL query seems a way to solve this problem. As described in the Grails documentation (executeQuery section) the paginate parameters can be added as extra parameters to executeQuery.
User.executeQuery("select distinct user from User user", [max: 2, offset: 2])
this way you can still use criteria and pass in list/pagination paramaters
User.createCriteria().listDistinct {
maxResults(params.max as int)
firstResult(params.offset as int)
order(params.order, "asc")
}
EDIT: Found a way to get both! Totally going to use it now
http://www.intelligrape.com/blog/tag/pagedresultlist/
If you call createCriteria().list() like this
def result=SampleDomain.createCriteria().list(max:params.max, offset:params.offset){
// multiple/complex restrictions
maxResults(params.max)
firstResult(params.offset)
} // Return type is PagedResultList
println result
println result.totalCount
You will have all the information you need in a nice PagedResultList format!
/EDIT
Unfortunately I do not know how to get a combination of full results AND max/offset pagination subset in the same call. (Anyone who can enlighten on that?)
I can, however, speak to one way I've used with success to get pagination working in general in grails.
def numResults = YourDomain.withCriteria() {
like(searchField, searchValue)
order(sort, order)
projections {
rowCount()
}
}
def resultList = YourDomain.withCriteria() {
like(searchField, searchValue)
order(sort, order)
maxResults max as int
firstResult offset as int
}
That's an example of something I'm using to get pagination up and running. As KoK said above, I'm still at a loss for a single atomic statement that gives both results. I realize that my answer is more or less the same as KoK now, sorry, but I think it's worth pointing out that rowCount() in projections is slightly more clear to read, and I don't have comment privileges yet :/
Lastly: This is the holy grail (no pun intended) of grails hibernate criteria usage references; bookmark it ;)
http://www.grails.org/doc/1.3.x/ref/Domain%20Classes/createCriteria.html
Both solutions offered here by Ruben and Aaron still don't "fully" work for pagination
because the returned object (from executeQuery() and listDistinct) is an ArrayList
(with up to max objects in it), and not PagedResultList with the totalCount property
populated as I would expect for "fully" support pagination.
Let's say the example is a little more complicated in that :
a. assume Role has an additional rolename attribute AND
b. we only want to return distinct User objects with Role.rolename containing a string "a"
(keeping in mind that a User might have multiple Roles with rolename containing a string "a")
To get this done with 2 queries I would have to do something like this :
// First get the *unique* ids of Users (as list returns duplicates by
// default) matching the Role.rolename containing a string "a" criteria
def idList = User.createCriteria().list {
roles {
ilike( "rolename", "%a%" )
}
projections {
distinct ( "id" )
}
}
if( idList ){
// Then get the PagedResultList for all of those unique ids
PagedResultList resultList =
User.createCriteria().list( offset:"5", max:"5" ){
or {
idList.each {
idEq( it )
}
}
order ("username", "asc")
}
}
This seems grossly inefficient.
Question : is there a way to accomplish both of the above with one GORM/HQL statement ?
You can use
User.createCriteria().listDistinct {
maxResults 10
}
Thanks for sharing your issue and Kok for answering it. I didn't have a chance to rewrite it to HQL. Here is my solution (workaround): http://ondrej-kvasnovsky.blogspot.com/2012/01/grails-listdistinct-and-pagination.html
Please tell me if that is useful (at least for someone).