对嵌套元素运行 hql 查询将返回"unexpected AST node"



当尝试使用通用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);

但是,尝试在 grail 中运行以下代码会抛出 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 请求中是否缺少某些内容?

进一步说明 :

  • 我正在使用圣杯 2.3.4
  • 我在访问圣杯代码中p.owner.contract.isActive的信息没有问题
  • 产品始终具有所有者
  • 有些业主根本没有合同(字段为空(
  • 所有者最多有 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

可能相关

最新更新