GORM Criteria - Using SQL's "Having" Clause

I have a dummy project cafeteria, where I have three domain classes: User, Productand Transaction.

The classes are defined here:

class User {

    String name
    int employeeId
    long balance = 800
    static constraints = {
        balance(max: 800L)
    }   
}

class Product {

    String type 
    int quantityInStock
    float price
    static constraints = {
    }
}

class Transaction {

    int quantityBought
    static belongsTo = [user: User, product: Product]
    static constraints = {
    }
}

Now I want to find out the number / list of users who bought more, say, 2 products . How to do this using Grails createCriteria?

This is what I tried:

Transaction.createCriteria().list(){
    projections {
        groupProperty('user')
        'product' {
            count('id','numberOfPurchases')
        }
    }
    gt('numberOfPurchases',2)
}

But this leads to the following error:

Stacktrace:

org.hibernate.QueryException: could not resolve property: numberOfPurchases of: cafeteria.dummy.Transaction 
at grails.orm.HibernateCriteriaBuilder.invokeMethod(HibernateCriteriaBuilder.java:1618)                    
at Script1.run(Script1.groovy:4)                                                                           
at org.grails.plugins.console.ConsoleService.eval(ConsoleService.groovy:37)                                
at org.grails.plugins.console.ConsoleController.execute(ConsoleController.groovy:59)                       
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:195)   
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)                          
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)                         
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)                         
at java.lang.Thread.run(Thread.java:745)                                                                   

How can I access this alias numberOfPurchasesoutside the projection block to use it in gt?

+4
source share
1 answer

GORM Hibernate, Hibernate having clause Criteria API. , numberOfPurchases , , where, where. JPA .

, GORM, . , .

:

SELECT DISTINCT this_.user_id FROM transaction this_ where 2 < (SELECT count(sub_.id) FROM transaction sub_ WHERE sub_.user_id=this_.user_id)

GORM :

import org.hibernate.criterion.DetachedCriteria
import org.hibernate.criterion.Projections
import org.hibernate.criterion.Restrictions
import org.hibernate.criterion.Subqueries

DetachedCriteria subQuery = DetachedCriteria.forClass(Transaction, 'sub').with {
    setProjection Projections.count('sub.id')
    add Restrictions.eqProperty('sub.user', 'this.user')
}

List<User> users = Transaction.createCriteria().list() {
    projections {
        distinct("user")
    }
    add Subqueries.lt(2l, subQuery)
} 
+2

All Articles