代码之家  ›  专栏  ›  技术社区  ›  anschoewe

休眠条件-提取单个对象

  •  3
  • anschoewe  · 技术社区  · 16 年前

    我正在使用Hibernate(Gorm)进行Grails项目。我有以下域模型:

    ClientContact {
       static hasMany = [owners: Person]
       static belongsTo = [Person]
    }
    
    Person {
       static hasMany = [clientContacts: ClientContact]
    }
    

    当我试图取回所有 ClientContacts 与特定所有者( Person )我遇到了一些有趣的问题。我使用以下查询条件:

    def query = {
       owners {
          eq("id", Long.parseLong(params.ownerId))
       }
    }
    def criteria = ClientContact.createCriteria()
    def results = criteria.list(params, query) 
    

    问题是当我迭代 客户联系方式 在结果中,他们只有 一个拥有者 -事实上,大多数人都有很多其他的主人。给出了什么?我知道Hibernate/Gorm使用的是懒惰的抓取,但我认为它可以在 ClientContact 当我试图接近他们的时候。

    有什么想法吗?我想继续使用 列表() 函数,因为它提供了一些不错的分页功能。

    3 回复  |  直到 7 年前
        1
  •  3
  •   Pawel Gwozdz    13 年前

    我知道这个线程很旧,但是我今天遇到了完全相同的问题,解决方案似乎是使用别名,因此:

    def query = {
            owners {
                    eq("id", Long.parseLong(params.ownerId))
            }
    }
    

    可以尝试:

    def query = {
            createAlias("owners", "o")
            eq("o.id", Long.parseLong(params.ownerId))
    }
    

    第一个查询创建左外部联接,第二个查询创建内部联接。有关详细说明,请参阅此链接: http://adhockery.blogspot.com/2009/06/querying-by-association-redux.html

        2
  •  0
  •   Ken Gentle    16 年前

    两个快速观察:

    1. [Grails文档]( http://grails.org/doc/1.0.x/guide/5.%20Object%20Relational%20Mapping%20(GORM).html#5.2.1.3 多对多)表示 多对多 关联必须手动编码,默认的脚手架不会这样做。
    2. 您可能需要使用 eqId() 标准见 createCriteria
        3
  •  0
  •   billjamesdev    16 年前

    ID和版本是所有GORM类的特殊属性。您不需要在类声明中指定它们,并且不能在它们中使用标准条件。

    你肯定需要使用eqid标准

       def query = {
              owners {
                    eqId(Long.parseLong(params.ownerId))
              }
       }
       def criteria = ClientContact.createCriteria()
       def results = criteria.list(params, query)
    
    推荐文章