【问题标题】:Grails Gorm Query RestrictionGrails Gorm 查询限制
【发布时间】:2015-06-11 04:32:37
【问题描述】:

我有两个域

class ProductQuantity {
    Integer quantity

    static belongsTo = [productSize: ProductSize]
}

class ProductSize {

    String size

    static hasMany = [productQuantities : ProductQuantity]
}

我正在尝试构建一个查询,通过 productSize 获取所有 ProductQuantity。我有以下有效的查询。

def productSize = ProductSize.findAllById(1);
def productQuantities = ProductQuantity.findAllByProductSize(productSize)

我希望在单个查询中而不是两个单独的查询中获取 ProductQuanties。

【问题讨论】:

    标签: grails grails-orm


    【解决方案1】:
    ProductQuantity.createCriteria().list {
        eq 'productSize', ProductSize.load(1)
    }
    

    ProductQuantity.withCriteria {
        eq 'productSize', ProductSize.load(1)
    }
    

    ProductQuantity.where {
        productSize == ProductSize.load(1)
    }.list()
    

    ProductQuantity.findAll("from ProductQuantity where productSize = ?", [ProductSize.load(1)])
    

    【讨论】:

    • 您使用负载的任何特殊原因?
    • loadget 更有意义。 get 强制进行数据库查询,可能包括许多列、大字符串等。所有ProductSize 实例用于获取其id 以用作最终SQL 中的外键。 get 效率低下,因为您丢弃了从数据库中检索到的所有数据,而只使用您已经知道的一个值 - id。使用load(),您将获得一个 Hibernate 代理。它具有id 值,如果您访问任何其他属性,它将使用它来检索完整实例。但既然你不会,就没有不必要的数据库访问。
    【解决方案2】:

    是的,你可以通过createCriteria 得到这个,比如 --

    def productQuantities = ProductQuantity.createCriteria().list() {
        productSize {
            eq('id', 1)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      相关资源
      最近更新 更多