如何检查对象是否在域对象的集合内?
在对我的应用程序的请求中,我经常获得应该关联的对象的 ID。但是我必须检查一下它们是否是。
示例场景: A 类和 B 类相关联:
A {
static hasMany = [bs: B]
}
在我的请求中,我将获得援助和投标。 我通常做的是:
def a = A.get(aid)
def b = a.bs.find {it.id == bid}
进行此检查的更好方法是什么?从性能的角度来看?
谢谢
In requests to my application i often get ids of the objects, which should be associated. However I have to perform a check to see if they are.
Example scenario:
Class A and B are associated:
A {
static hasMany = [bs: B]
}
In my request I will get aid and bid.
What I usually do is:
def a = A.get(aid)
def b = a.bs.find {it.id == bid}
What would be a better way to make this check? From performance point of view?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果 B 中定义了 ownTo = [ a : A ] ,那么您可以执行以下操作:
这不会像您的代码那样对所有集合元素进行迭代。本质上,它与 erturne 的解决方案相同,但这实际上加载了对象。
If B has a belongsTo = [ a : A ] defined in it, then you can do this:
This won't do an iteration over all the sets elements like your code. Essentially, it's the same as erturne's solution, but this actually loads the object.
我的第一个倾向是转到 HQL 并使用 count() 来查看它是否存在。可能有更优雅的方法来实现同样的事情(也许使用 withCriteria),但我的第一次破解看起来像:
我认为这会非常有效,尽管任何时候你正在考虑提高性能,最好对不同的实现进行测量所以你可以自己比较它们。我将把它作为练习留给读者。 ;-)
编辑:我认为它很有效,因为我将繁重的工作留在了数据库中,而不是通过网络提取 A 和 B 实例的数据、在内存中创建实例或迭代结果。
My first inclination is to drop to HQL and use count() to see if it exists. There may be more elegant ways to achieve the same thing (perhaps using withCriteria) but my first crack at it looks like:
I think that would be pretty efficient, although anytime you're looking at improving performance it's best to take measurements of different implementations so you can compare them for yourself. I'll leave that as an exercise for the reader. ;-)
EDIT: I think it's efficient because I've left the heavy lifting in the database rather than pulling data for instances of A and B across the network, creating instances in memory, or iterating over results.