如何在 HQL 中进行此查询 运行

How to make this query run in HQL

更新 Account_Phone 设置 is_Primary_Phone=(当 account_id=10 和 phone_id=20 时 is_Primary_Phone=true 否则 is_Primary_Phone =假结束)

您可以通过以下两种方式:

第一种方式:将您的查询封装在一个(hibernate 的)ocject Query 中并使用 execute 方法。 (Account_Phone 必须是 class 映射到真正的 table)

第二种方式:将逻辑应用于您的class集合,然后使用session.merge(或session.saveOrUpdate)更新您的数据库。

在 Grails 3.0.9 中,我将执行此操作添加到查询中

AccountPhone.executeUpdate("update AccountPhone ap set ap.isPrimaryPhone=case when (account_id=? and phone_id=?) THEN true ELSE false end where account_id=?",[account.id,params?.long('phoneNo'),account.id])

CASE 语法是:CASE {operand} WHEN {test_value} THEN {match_result} ELSE {miss_result} END 请参阅 Hibernate HQL 文档。

您还可以这样做:CASE WHEN {test_value} THEN {match_result} ELSE {miss_result} END

不能做的是在 {match_result}{miss_result}: ... THEN isPrimaryPhone = true ELSE isPrimaryPhone = false END

不同的数据库系统对布尔值的处理方式不同。但通常您查询的 CASE 表达式为:CASE WHEN account_id = :account AND phone_id = :phone THEN 1 ELSE 0 END

这是一个完整的例子:

def hql = """
UPDATE AccountPhone 
SET isPrimaryPhone = CASE WHEN account_id = :account AND phone_id = :phone THEN 1 ELSE 0 END 
WHERE account_id = :account
"""

AccountPhone.executeUpdate(hql, [account: account.id, phone: params.long('phoneNo')])