using Hibernate, I'd like to update a data in the database based on conditions, but I got the following error : "node to traverse cannot be null"
Here is my database description :
Account: id, email, password
Member : id, account, team
Team: id, current (and a reference to member => members)
Here is my JPA :
UPDATE Team t SET t.current = :current LEFT JOIN t.members m WHERE t.current = :current_true AND m.account = :account
What am I doing wrong? If i move the LEFT JOIN to before the SET :
UPDATE Team t LEFT JOIN t.members m SET t.current = :current WHERE t.current = :current_true AND m.account = :account
I got : "expecting SET, found LEFT"
If I remove the join :
UPDATE Team t SET t.current = :current WHERE t.current = :current_true AND t.members.account = :account
I got : "Illegal attempt to dereference collection".
What is the correct way to update values ?
Thanks for your help!
An UPDATE statement can include JOIN operations. An UPDATE can contain zero, one, or multiple JOIN operations. The UPDATE affects records that satisfy the JOIN conditions.
SQL UPDATE JOIN could be used to update one table using another table and join condition.
SQL Server UPDATE JOIN syntax In this syntax: First, specify the name of the table (t1) that you want to update in the UPDATE clause. Next, specify the new value for each column of the updated table. Then, again specify the table from which you want to update in the FROM clause.
JOIN clause in MySQL is used in the statement to retrieve data by joining multiple tables within a single query. The UPDATE JOIN is a MySQL statement used to perform cross-table updates that means we can update one table using another table with the JOIN clause condition.
The JPA 2.0 specification in chapter 4 contains details of all supported features in JPQL. This is the definition of the "update" statement:
The syntax of these operations is as follows:
update_statement ::= update_clause [where_clause]
update_clause ::= UPDATE entity_name [[AS] identification_variable]
SET update_item {, update_item}*
update_item ::= [identification_variable.]{state_field | single_valued_object_field} =
new_value
new_value ::=
scalar_expression |
simple_entity_expression |
NULL
As you can see, support for multiple entities is not stated here. I guess you will have to find a different way to do it, perhaps create a method that selects the entities that you want to update first, and then iterate over the results setting the values. Or you could use a native SQL update.
Use a subquery:
(not tested)
UPDATE Team t SET t.current = :current
WHERE t.id in (select t1.id from Team t1 LEFT JOIN t1.members m WHERE t1.current = :current_true AND m.account = :account)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With