2016-02-09 37 views
0

我有兩個班的MS SQL Server UPDATE語句:與加入Spring和Hibernate

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

感謝您的幫助!

+0

您無法在JPQL UPDATE語句中添加FROM子句,因爲任何文檔都會顯示給您。 http://www.datanucleus.org/products/accessplatform_4_2/jpa/jpql.html#JPQL_UPDATE_Queries –

+0

尼爾,非常感謝sooooo爲您提供幫助。根據您的意見,我在SO發現了另一篇文章,解決了我的問題。基本上,我需要使用子查詢。 http://stackoverflow.com/questions/6201895/update-value-with-join – curious1

回答

1

根據Nei Stockton提供的信息,我做了進一步的搜索,並在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) 

乾杯!