在Spring和Hibernate中使用JOIN的MS SQL Server UPDATE语句

时间:2016-02-09 15:40:12

标签: spring hibernate jpa

我有两个班级:

Course {
  ...
  private List<Student> students;
  private String var1;
  ...
}

Student {
  private Long id;
  ...
}

在我的代码中,我能够动态生成以下查询并成功获得结果:

SELECT c.var1 FROM Course c, IN (c.students) s WHERE s.id = :sid

现在我想使用以下动态生成的查询进行更新:

UPDATE c SET c.var1 = 'newvalue' FROM Course c, IN (c.students) s WHERE s.id = :sid

为此,我总是遇到错误:

org.springframework.dao.InvalidDataAccessApiUsageException: node to traverse cannot be null!; nested exception is java.lang.IllegalArgumentException: node to traverse cannot be null!

我提出上述UPDATE查询的原因是因为我读了这篇SO帖子:

How can I do an UPDATE statement with JOIN in SQL?

这是我的代码:

Query query = em.createQuery("UPDATE c SET c.var1 = 'newvalue' FROM Course c, IN (c.students) s WHERE s.id = :sid");
query.setParameter("sid", 10);
query.executeUpdate();

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

根据内斯托克顿的信息,我做了进一步的搜索,发现在SO的另一篇文章解决了我的问题。

Update value with join

基本上,我需要使用类似于上面帖子中给出的以下子查询:

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)

干杯!