Grails:如何减少数据库查询

时间:2013-11-27 08:38:14

标签: mysql sql hibernate grails hql

我使用进度条显示任务的完成百分比。要获得完成百分比,我使用countBy方法:

DomainA.countByZ(z) > 0 ? Status.COMPLETE : Status.INCOMPLETE

我有十个这样的查询。

每当我完成状态时,我会将计数器加1,最后除以10得到平均值。

获得达到10个数据库查询的百分比

select count(*) as y0_ from domain_a this_ where this_.z_id=?
select count(*) as y0_ from domain_b this_ where this_.z_id=?
...

有没有办法减少查询次数?(通过使用hql查询或任何其他方式来获得平均值或计数)。

我用Google搜索但未获得相关信息。

1 个答案:

答案 0 :(得分:1)

如果我没有弄错,你不能使用HQL来查询没有关系的实体,因此解决方案是在这种情况下使用本机sql。您可以在服务中执行此操作:

import groovy.sql.Sql

class MyService {
  def dataSource

  int myCalc() {
    Sql sql = new Sql(dataSource)
    String query = """
select count(*) tot1, 
       (select count(*) from domain_class2) as tot2
  from domain_class1
"""
    def row = sql.firstRow(query)
    //access properties directly
    println row.tot1
    println row.tot2
  }
}
相关问题