2

我有一个对象,我必须从中过滤某些属性,其中一些属性也可能是“null”。我有一个 Filter 对象和一个 Product 对象。

在 Filter 对象中,我有一些反映 Product 对象的属性,可以填写或留空。这里是关于类的简短视图。

Product: String name, Boolean isEmpty, ...., belongsTo [Producer, Distributor]...


Filter: Boolean isEmpty, ... belongsTo [Producer, Distributor]...

使用此过滤器,我可以搜索具有特定属性(空、生产者、分销商)的所有产品。

我有一个导出功能,我可以在其中选择过滤器,并根据产品的选择输出信息。

由于所有这些属性都可以为空,但也包含一个值,我首先想到构造一个自己的搜索查询(组合字符串等)来构造一个 SQL 字符串,然后使用 Product.findAll(string_query, string_params)。但是由于这很乏味,我现在将其更改为这样的:

if(filter.producer)
    prods = Product.findAllWhere(producer:filter.producer)
if(filter.distributor)
    prods =  prods.findAll {it.distributor == filter.distributor}
if(filter.isEmpty!=null) //as it could be NULL but also false/true
    prods =  prods.findAll {it.isEmpty == filter.isEmpty}

但是,如果我要过滤 10-15 个属性,这将成为一项更大的任务。我对 Grails 或 Groovy 不是很有经验,但我想这可以更容易解决,对吧?

4

1 回答 1

5

我相信您会发现 Grails Criteria 查询是完成此类任务的一种非常好的方法。看:

当表示为条件查询时,您的示例可能看起来像这样:

def prods = Product.createCriteria().list {
    if(filter.producer) eq("producer", filter.producer)
    if(filter.distributor)  eq("distributor", filter.distributor)
    if(filter.isEmpty != null) eq("isEmpty", filter.isEmpty)
}
于 2013-02-13T20:18:10.167 回答