【问题标题】:How to create a custom function that returns a closure of grails criteria methods如何创建返回 grails 标准方法闭包的自定义函数
【发布时间】:2018-03-29 09:22:59
【问题描述】:

我正在尝试将顶部的代码块抽象出来,使其看起来像底部的代码块。

if (params.xId) {
    and {
       'in'(aggregateClassReference, hierarchy['x'])
        eq(aggregateIdReference, params.xId as Long)
     }
}
if (params.yId) {
   and {
       'in'(aggregateReference, hierarchy['y'])
        eq(aggregateIdReference, params.yId as Long)
   }
}

...

if (params.xId) { belongsToHierarchy('x', params.xId as Long) }
if (params.yId) { belongsToHierarchy('y', params.yId as Long) }

我正在使用 gorm 条件查询,但我不想要这些大块代码。有没有办法在自定义函数中返回这些条件查询的闭包?现在的问题是我把下面的代码块放在

def criteria = DetachedCriteria.build(...)

然后我做了一个

criteria.list(...)

执行。以某种方式返回一个闭包会很棒

 and {
    'in'{...}
    eq {...}
 }

在构建中的自定义函数中,但我还没有弄清楚。对 grails 有点陌生。任何指导我的见解将不胜感激:)

【问题讨论】:

标签: hibernate grails grails-orm criteria


【解决方案1】:

有很多方法可以解决这个问题。您没有展示足够的背景来确定最佳解决方案就是您正在做的事情,但鉴于那里有什么,我可以展示一些可能有帮助的东西。

如果您想使用条件查询,那么不要使用类似这样的查询...

def results = SomeDomainClass.withCriteria {
    if (params.xId) {
        and {
            'in'(aggregateClassReference, hierarchy['x'])
            eq(aggregateIdReference, params.xId as Long)
        }
    }
    if (params.yId) {
       and {
           'in'(aggregateReference, hierarchy['y'])
            eq(aggregateIdReference, params.yId as Long)
       }
    }
}

你可以做这样的事情......

def results = SomeDomainClass.withCriteria {
    if (params.xId) {
        belongsToHierarchy 'x', params.long('xId'), delegate
    }
    if (params.yId) {
        belongsToHierarchy 'y', params.long('yId'), delegate
    }
}

// ...

// it isn't clear from your example if
// aggregateClassReference and hierarchy are local
// variables in the context where the criteria
// query is being initialized or if they are
// instance variables.  If they are instance variables
// the code below will work.  If they are local
// variables then they might need to be passed as
// arguments into this belongsToHierarchy method...

void belongsToHierarchy(String arg, long id, delegate) {
    def query = {
        // not sure why you had the "and" in your example, but
        // I will leave it here assuming there is a reason...
        and {
            'in' aggregateClassReference, hierarchy[arg]
            eq aggregateIdReference, id
        }
    }
    query.delegate = delegate
    query()
}

【讨论】:

  • 我展示了一个标准查询,因为这是您在问题中使用的。根据问题中不清楚的一些细节,另一个具有一些不错好处的选项可能是利用分离条件查询是可组合的这一事实。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-01
  • 1970-01-01
  • 2018-04-16
  • 2015-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多