java - 对嵌套元素运行 hql 查询返回“意外的 AST 节点”
问题描述
当尝试使用泛型executeUpdate(query)
方法更新我的 java 对象时,grails 抛出 NullPointer 异常,说明:
意外的 AST 节点:。
我的对象关系结构如下:
Class Product implements Serializable {
String name
Integer priority
static belongsTo = [owner: Owner]
static mapping = {owner fetch: 'join'}
}
Class Owner implements Serializable {
String name
Contract contract
static hasMany = [product: Product]
}
Class Contract implements Serializable {
Boolean isActive
}
我已经在我的数据库上成功运行了以下 SQL 请求:
UPDATE product SET priority = IF(
(SELECT co.is_active FROM owner o
JOIN contract co
ON co.id = o.contract_id
WHERE o.id = product.dealership_id) = 1
, 10, 0);
但是,尝试在 grails 中运行以下代码会引发 NPE:
def hqlQuery = 'update Product p set p.priority = (case when p.owner.contract.isActive then 10 else 0 end)'
def result = Product.executeUpdate(hqlQuery)
这是为什么 ?我的类映射或 HQL 请求中是否缺少某些内容?
进一步说明:
- 我正在使用 grails 2.3.4
- 我可以毫无问题地访问
p.owner.contract.isActive
我的 grails 代码中的信息 - 产品总是有所有者
- 一些业主根本没有合同(字段为空)
- 所有者最多有 1 个有效合同。但是,在数据库中,几个旧合同可以引用同一个所有者。
解决方案
出于好奇,我昨晚深夜设置了一个示例站点,因为它应该可以工作
我认为这可能与事物的定义方式以及您尝试更新的方式有关:
Product: static belongsTo = [owner: Owner]
Owner: static hasMany = [product: Product]
认为可能是问题的核心,因为您的更新从产品开始或需要更新产品,但是当它很好地击中所有者时,这可能有很多该产品。注意到在查询中为我本地出现的内部连接。
这似乎对我有用:
def hqlQuery = """update Product as p
set p.priority = case when
exists(select 1 from Owner o where o = p.owner and o.contract.isActive is true)
then 10
else 0
end
where id > 0
"""
def result = Product.executeUpdate(hqlQuery)
def found = Product.findAll().priority