简体   繁体   中英

Error in Update JPA Query

I have a problem with this query when run is as follows

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());

This is the exception that gets thrown when running

  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.

Try something like this, putting it into a subquery, assuming that histAsociados is an entity inside Equipo entity:

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())

Also, could you please try putting some simple names to the attributes of entities. That increases readability.

According to the JPA specification, your syntax cannot be correct. The simplified form of the syntax for the UPDATE statement can be stated as follows:

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

Applying this for your case it might look like:

"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())

In the above statement, I was guessing that HistAsociado could be an Entity name; otherwise you have to correct it!

The result of the subquery must also be a single value.

Warning: The modified statement would update all the records in the table as there is no WHERE condition is specified.

So, use this as a hint to solve the problem and don't use it before you have corrected the guessing and added the WHERE condition.

For more information and examples, you could read JPA update statement and this one too .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM