【问题标题】:Is there a way to convert this HQL to Criteria?有没有办法将此 HQL 转换为标准?
【发布时间】:2014-12-26 11:48:19
【问题描述】:

这是我要转换的 HQL:

UserRequest.executeQuery("Select ur.request from UserRequest ur 
  where ur.user = :user and ur.request.type is null 
  order by ur.request.dateCreated DESC",
[user: user],
[max: params.max?: 10, offset: params.offset?: 0])

我尝试使用下面的代码将其转换为criteria,但它给了我一个错误No property request.type found

def list = UserRequest.createCriteria().list(max: params.max?: 10, offset: params.offset?: 0) {
     eq("user", user)
     isNull(request.type)
     order("request.dateCreated", "DESC")
}

转化的动机

除了在使用 HQL 时必须编写单独的查询来获取总数(用于分页)之外,我要将其转换为条件的另一个原因是因为我需要根据参数过滤此查询的结果。例如:

def list = UserRequest.createCriteria().list(max: params.max?: 10, offset: params.offset?: 0) {
     eq("user", user)
     isNull("request.type")

     if (params.filtertype == "color") 
       ilike("request.color", "%${params.filtervalue}%")
     order("request.dateCreated", "DESC")
}

如果我尝试使用 HQL 执行上述操作,它会变得更加麻烦。

更新

这是我的班级结构

class User {
    transient springSecurityService
    String username
    String password
}

Class Request {
    String type
}

class UserRequest implements Serializable{
    User user
    Request request

    static mapping = {
        id composite: ['user', 'request']
        version false
    }

    //equals & hashcode

    static UserRequest create (User user, Request request, boolean flush = true) {
        def d = new UserRequest (user: user, request: request)
                d.save(flush: flush, insert: true)
    }
}

【问题讨论】:

    标签: hibernate grails hql hibernate-criteria


    【解决方案1】:

    由于您的条件查询涉及关联,请尝试以下操作:

    def list = UserRequest.createCriteria().list(max: params.max?: 10, offset: params.offset?: 0) {
         eq("user", user)
         request {
             isNull("type")
             order("dateCreated", "DESC")
         }
    }
    

    还有一个使用createAlias() 的语法变体。您可能会发现这更容易使用,具体取决于查询的最终结构。有关更多示例,请参阅此处的“查询关联”部分:http://grails.org/doc/latest/guide/GORM.html#criteria

    【讨论】:

      猜你喜欢
      • 2014-09-14
      • 1970-01-01
      • 2022-07-06
      • 2011-07-30
      • 2021-10-06
      • 2020-01-24
      • 2019-01-31
      • 1970-01-01
      • 2019-07-12
      相关资源
      最近更新 更多