【问题标题】:Grails GORM : Find All with AssociationsGrails GORM:使用关联查找所有内容
【发布时间】:2015-03-19 20:13:09
【问题描述】:

我正在尝试获取特定年龄段的所有用户。 每个User 都有一个User 表和一个Profile 表。

最小的User 域类:

class User {

  static hasOne = [profile: Profile]

}

最小的Profile 域类:

class Profile {

  static belongsTo = [user: User]

  Integer age

  static constraints = {
    age(range: 18 .. 150)
  }

}

最小的UserService 域类:

class UserService {

  def list() {

    def users = User.findAll{
      gender in whichGenderList
      profile.age in 18 .. 150 /* Problem */
    }

}

在与Problem 一致的情况下,我在浏览器中收到以下异常:

URI /foo/browse
Class org.hibernate.QueryException
Message could not resolve property: profile_alias0 of: foo.Profile

问题:UserService 中,我如何从每个UserProfile 表中选择它的年龄?

我正在使用:

  • Grails 2.4.4

谢谢!

【问题讨论】:

    标签: grails grails-orm


    【解决方案1】:

    像这样使用条件查询:

     def users = User.createCriteria().list(){
         inList('gender', whichGenderList)
         profile{
              inList('age', 18 .. 150)
         }
    
        }
    

    【讨论】:

      【解决方案2】:

      如果有疑问,请使用 HQL:

      User.findAll(
          "from User u where u.gender in :genders and u.profile.age between :minAge and :maxAge",
          [genders: [], minAge: 18, maxAge: 150]
      )
      

      【讨论】:

      • 我试图避免使用 HQL!什么时候可以。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 2017-01-14
      • 1970-01-01
      • 2015-01-23
      相关资源
      最近更新 更多