java 使用 join 更新值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6201895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Update value with join
提问by Cyril N.
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"
使用 Hibernate,我想根据条件更新数据库中的数据,但出现以下错误:“要遍历的节点不能为空”
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 :
这是我的 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 :
我究竟做错了什么?如果我将 LEFT JOIN 移到 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"
我得到:“期待 SET,找到 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!
谢谢你的帮助!
采纳答案by Edwin Dalorzo
The JPA 2.0 specification in chapter 4 contains details of all supported features in JPQL. This is the definition of the "update" statement:
第 4 章中的 JPA 2.0 规范包含 JPQL 中所有支持功能的详细信息。这是“更新”语句的定义:
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.
如您所见,此处未说明对多个实体的支持。我想你将不得不找到一种不同的方法来做到这一点,也许创建一个方法来选择你想要首先更新的实体,然后迭代设置值的结果。或者您可以使用本机 SQL 更新。
回答by natasha.pecanova
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)