这是我尝试转换的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)
}
}
答案 0 :(得分:0)
由于您的条件查询涉及关联,请尝试以下操作:
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