优化 Grails 查询

Optimize Grails Queries

我正在尝试优化我的 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)
}

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

有什么想法吗?

我使用

比较了你查询的三个版本
  • Grails 2.4.4,Grails 应用程序中缓存的默认设置
  • PostgreSQL 8.4,SQL 语句日志记录已打开到 count/see SQL 查询。

第一个版本在 Grails 域上使用 两次调用 class:

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 查询

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

  Element b = query.get()

  render(b.toString())
}

第一个导致两个 SQL个查询,其他的只会发送一个查询到数据库(使用从 ElementCatalog) 的内连接。

至于readability/expressiveness,选择第3版:用一行表达你的意图,是最简洁的版本。

关于性能,选择第二版或第三版。在高负载下,许多并发 users/requests,查询的数量确实很重要。这可能不是所有应用程序的问题。

总之,为了表现力,我总是选择第三版;如果查询条件随着时间的推移变得更加复杂,它将扩展。


更新

第一版使用的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= limit 
Parameter:  = 'a',  = '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= and this_.pos= limit 
Parameter:  = '10',  = '2',  = '1'

第二版和第三版的SQL声明:

select this_.id as id1_2_1_, this_.version as version2_2_1_, this_.catalog_id as catalog_3_2_1_, this_.date_created as date_cre4_2_1_, this_.last_updated as last_upd5_2_1_, this_.pos as pos6_2_1_, this_.remark as remark7_2_1_, catalog_al1_.id as id1_1_0_, catalog_al1_.version as version2_1_0_, catalog_al1_.date_created as date_cre3_1_0_, catalog_al1_.last_updated as last_upd4_1_0_, catalog_al1_.name as name5_1_0_, catalog_al1_.remark as remark6_1_0_ 
  from element this_ inner join catalog catalog_al1_ 
    on this_.catalog_id=catalog_al1_.id 
    where (catalog_al1_.name=) and this_.pos=
Parameter:  = 'a',  = '2'