【问题标题】:Grails Hibernate criteria - Checking if a relation existsGrails Hibernate 标准 - 检查关系是否存在
【发布时间】:2015-08-10 09:42:33
【问题描述】:

我正在尝试执行过滤器来查找某个对象是否与另一个对象有关系。我有一个对象Component

class Component { 
    long id
    String name
}

一个组件被一个页面使用。

class Page {
    long id
    static hasMany = [components : Component]
}

我将如何构建一个休眠条件来检查我的组件是否与任何页面有关系?一个组件可以被多个页面使用。到目前为止,我能想到的只是:

Component.createCriteria().list {
    inList("id", Page.list().components);
}

但这根本不会很好地扩展。所以我想知道是否有更简单的方式来表达“如果我的对象被这个对象使用”?

【问题讨论】:

    标签: hibernate grails


    【解决方案1】:
    Page.createCriteria().count {
        components {
            eq("id", yourComponent.id)
        }
    }
    

    此查询为您提供包含 yourComponent 的所有页面的计数。如果这是 0,那么 yourComponent 就没有关联到任何页面。

    编辑____________________________________________________________

    不,因为ComponentPage 没有关系。

    但如果你想要这个,那么我的建议是formula column。在这种关系中,您有三个表componentpage 和关系表page_components

    例如,

    class Component { 
        long id
        String name
        Boolean isRelatedWithAnyPage
    
        static mapping = {
            isRelatedWithAnyPage formula: "(select (count(*)>0) from page_components pc where pc.component_id = id)"
        }
    }
    

    注意:- 我没有尝试过,可能是你需要更改公式中的 sql 查询。

    【讨论】:

    • 有没有办法将它作为第一个条件的一部分插入?
    • 我已经编辑了我的帖子。看一看。希望这会有所帮助。
    • 对你的第一个建议采取了类似的方法,所以我想我会接受这个。干杯!
    【解决方案2】:

    您可以将存在与子查询一起使用。

    def subQuery = Page.where({
       components {
          eqProperty("id", "this.id") //this: is the root alias which refers to the Component
       }
       setAlias("page")
    })
    
    
    Component.createCriteria().list {
      exists(subQuery.id())
    }
    

    how to execute exists subqueries with grails criteria

    【讨论】:

      【解决方案3】:

      另一种方法是创建一个 PageComponent 域来匹配由 grails 自动创建的底层连接表并执行PageComponent.countByComponentId(componentId)

      【讨论】:

      • 这是一个很好的建议,但这不是我们在许多其他应用程序中遵循的惯例,所以我认为这不会通过代码审查!但感谢您的意见和合乎逻辑的建议 +1。
      猜你喜欢
      • 2019-01-10
      • 2021-05-06
      • 2020-06-21
      • 2015-01-29
      • 2014-08-24
      • 2014-01-15
      • 2020-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多