我有一个虚拟自助餐厅项目,其中我有三个域类: User
, Product
和 Transaction
。
这是类的定义:
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 = {
}
}
现在,我想找出购买了超过2个产品的用户列表的数量。我该如何使用Grails createCriteria进行操作?
这是我尝试的:
Transaction.createCriteria().list(){
projections {
groupProperty('user')
'product' {
count('id','numberOfPurchases')
}
}
gt('numberOfPurchases',2)
}
但给出以下错误:
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)
如何在投影块之外访问此别名numberOfPurchases
,以便在gt
中使用它?
内部GORM
使用Hibernate,目前Hibernate在Criteria
API中不支持having clause
。您无法获得numberOfPurchases
外部预测块的原因是将限制添加到子句的位置,并且无法在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)
}