优化Grails查询

时间:2015-03-17 19:53:22

标签: grails gorm database-performance

我试图在我的grails应用中优化速度。 我有这个:

Catalog a= Catalog.findByName('a');
Element b= Element.findByCatalogAndNumber(a,2);

这样我就可以找到b。

但我认为我可以使用这样的东西:

Element b= Element.createCriteria().get{
       catalog{
          eq("name",'a')
       }
       eq("number",2)
}

但是我不确定它是否会减少对数据库的查询,或者我只是愚弄自己并创建更大的文件并通过这样做来降低我的应用程序的速度。

任何想法?

1 个答案:

答案 0 :(得分:1)

我使用

比较了三个版本的查询
  • Grails 2.4.4,Grails应用程序中缓存的默认设置
  • PostgreSQL 8.4,已启用SQL语句日志记录来计算/查看SQL查询。

在Grails域类中使用两次调用的第一个版本:

def query1() {
  Catalog a = Catalog.findByName('a');
  log.info(a)

  Element b = Element.findByCatalogAndPos(a, 2);
  log.info(b)

  render(b.toString())
}

第二个使用标准

def query2() {
  Element b = Element.createCriteria().get {
    catalog {
      eq("name", "a")
    }
    eq("pos", 2)
  }

  render(b.toString())
}

最后一个使用 where query

def query3() {
  def query = Element.where {
    catalog.name == "a" && pos == 2
  }

  Element b = query.get()

  render(b.toString())
}

第一个产生两个 SQL查询,其他只会向数据库发送一个查询(使用Element到{{}的内部联接{1}})。

至于可读性/表现力,请选择第3版:它在一行中表达您的意图,并且它是最紧凑的版本。

至于性能,请选择第2版或第3版。在高负载,许多并发用户/请求下,查询的数量确实很重要。这可能不是所有应用程序的问题。

Anway,我总是选择第三版来表达;如果查询条件在一段时间内变得更加复杂,它将进行扩展。


更新

第一版使用的SQL语句:

Catalog

第2版和第3版的SQL语句:

select this_.id as id1_1_0_, this_.version as version2_1_0_, this_.date_created as date_cre3_1_0_, this_.last_updated as last_upd4_1_0_, this_.name as name5_1_0_, this_.remark as remark6_1_0_ 
  from catalog this_ 
  where this_.name=$1 limit $2
Parameter: $1 = 'a', $2 = '1'

select this_.id as id1_2_0_, this_.version as version2_2_0_, this_.catalog_id as catalog_3_2_0_, this_.date_created as date_cre4_2_0_, this_.last_updated as last_upd5_2_0_, this_.pos as pos6_2_0_, this_.remark as remark7_2_0_ 
  from element this_ 
  where this_.catalog_id=$1 and this_.pos=$2 limit $3
Parameter: $1 = '10', $2 = '2', $3 = '1'
相关问题