【问题标题】:Grails: How to reduce DB queriesGrails:如何减少数据库查询
【发布时间】:2013-11-27 08:38:13
【问题描述】:

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

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

我有十个这样的查询。

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

为了获得它命中十个数据库查询的百分比

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 查询或任何其他方式来获取平均值或计数)。

我用谷歌搜索了同样的信息,但没有得到相关信息。

【问题讨论】:

    标签: mysql sql hibernate grails hql


    【解决方案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
      }
    }
    

    【讨论】:

    • 我的logSql 是真的。我可以在控制台中看到我的DomainA.countByZ(z) DB,但控制台中未显示本机 sql DB 命中。我不知道 grails 是否显示本机 sql 命中。如何查看原生 sql DB 命中?
    • 在 log4j 配置中添加 groovy.sql 包作为级别 debug
    • 这给了我===2013-11-27 23:40:34,962 [http-bio-80-exec-5] DEBUG sql.Sql - select count(*) tot1, (select count(*) from achievement) as tot2, (select count(*) from article) as tot3, from address ===5======0=======18======== Hibernate: select count(*) as y0_ from address this_ Hibernate: select count(*) as y0_ from achievement this_ Hibernate: select count(*) as y0_ from article this_ ===5======0=======18======
    • 好像是一个查询,我没有确认。
    • 是的,一个查询。除非您调用方法,否则 Groovy 的 Sql 类不会创建查询。
    猜你喜欢
    • 2016-07-10
    • 2017-06-01
    • 2011-09-24
    • 2012-01-06
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    相关资源
    最近更新 更多