更新JPA查询时出错

时间:2016-05-04 01:54:55

标签: java jpa

运行时,我遇到此查询的问题

Query query = em.createQuery("UPDATE Equipo c JOIN c.histAsociados e SET e.horasTrabajadas = (CAST(c.horastd AS DECIMAL(18,2)) - (c.horastotales AS DECIMAL(18,2))) WHERE c.id=" + equipo.getId());

这是运行

时抛出的异常
  The SET identifier is missing from the UPDATE clause.  [39, 39] The equal sign must be specified.[16, 38]  The expression is invalid, which means it does not follow the JPQL grammar.[40, 43] The identification variable 'SET' cannot be a reserved word.[115, 115] The right parenthesis is missing from the sub-expression.[115, 115] The right parenthesis is missing from the sub-expression.[116, 126]  The expression is invalid, which means it does not follow the JPQL grammar.[133, 151] The query contains a malformed ending.

2 个答案:

答案 0 :(得分:0)

尝试这样的事情,将其放入子查询中,假设histAsociados是Equipo实体内的实体:

Query query = em.createQuery("UPDATE Equipo c SET c.histAsociados WHERE c.histAsociados.id in(select Equipo.id from Equipo c1 LEFT JOIN c1.histAsociados e WHERE e.horasTrabajadas = (CAST(c1.horastd AS DECIMAL(18,2)) - (c1.horastotales AS DECIMAL(18,2))) AND c1.histAsociados.id = e.id) AND c.id=:id).setParameter("id", equipo.getId())

另外,您可以尝试将一些简单的名称添加到实体的属性中。这增加了可读性。

答案 1 :(得分:0)

根据JPA规范,您的语法不正确。 UPDATE语句的简化形式可以表述如下:

  

UPDATE< entity_name> < identification_variable> SET< identification_variable&gt ;.< state_field> =< value> WHERE< condition>

将此应用于您的案例,它可能如下所示:

"UPDATE HistAsociado?? e SET e.horasTrabajadas = (SELECT (CAST(c.horastd AS DECIMAL(18,2)) - CAST(c.horastotales AS DECIMAL(18,2))) AS DIFF FROM Equipo c WHERE c.id= " + equipo.getId())

在上面的陈述中,我猜测 HistAsociado可能是实体名称;否则你必须纠正它!

子查询的结果也必须是单个值。

警告:由于未指定 WHERE 条件,修改后的语句将更新所有表中的记录。

因此,使用此作为解决问题的提示,在纠正猜测并添加 WHERE 条件之前不要使用它。

有关更多信息和示例,您可以阅读JPA update statementthis one too